10-10 5,878 views
ajax在提交请求到接收后台返回结果这段时间内,要是处理时间太长,用户会以为网页卡住,所以添加loading图是很有必要的。可通过ajax的beforeSend来实现。下面是完整代码:
- <html>
- <head>
- <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
- <title>ajax返回结果前等待loading</title>
- <style>
- body{
- margin: 0;
- padding: 0;
- }
- .div_alert_bg{
- width:100%;
- height:100%;
- position:fixed;
- left:0;
- top:0;
- z-index:2;
- opacity:0.3;
- background:#000;
- display: none;
- }
- .div_loading{
- width:100%;
- height:100%;
- position:fixed;
- left:0;
- top:0;
- z-index:3;
- display:none;
- }
- .div_loading_img{
- top: 50%;
- left: 50%;
- position: absolute;
- transform: translate(-50%, -50%);
- width:124px;
- }
- .div_content{
- width:100%;
- height:100%;
- position:fixed;
- left:0;
- top:0;
- z-index:1;
- }
- #submit{
- top: 50%;
- left: 50%;
- position: absolute;
- transform: translate(-50%, -50%);
- background-color:#d8f3ff;
- border:2px solid rgba(25,86,151,0.5);
- color:#000;
- font-size:1.2rem;
- height:2rem;
- width: 8rem;
- border-radius:10px;
- }
- </style>
- </head>
- <body>
- <div class="div_alert_bg"></div>
- <div class="div_loading">
- <div class="div_loading_img">
- <img width="100%" src="http://wx.karlew.com/ajaxLoading/img/loading.gif">
- </div>
- </div>
- <div class="div_content">
- <input id="submit" type="button" value="提交请求">
- </div>
- </body>
- </html>
- <script type="text/javascript" src="http://libs.useso.com/js/jquery/2.1.1/jquery.min.js"></script>
- <script type="text/javascript">
- $(document).ready(function(){
- $("#submit").click(function(){
- $.ajax({
- type: "GET",
- url: 'ajaxTset.php',
- beforeSend: function () {
- $(".div_alert_bg").show()
- $(".div_loading").show()
- },
- success: function (msg){
- $(".div_loading").hide()
- $(".div_alert_bg").hide()
- alert(msg)
- }
- })
- })
- })
- </script>
还有ajaxTest.php,为了让这个过程更加明显,我设置了2秒延时:
- sleep(2);
- echo "已成功提交";