ajax在提交请求到接收后台返回结果这段时间内,要是处理时间太长,用户会以为网页卡住,所以添加loading图是很有必要的。可通过ajax的beforeSend来实现。下面是完整代码:

  1. <html>  
  2. <head>  
  3. <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">  
  4. <title>ajax返回结果前等待loading</title>  
  5. <style>  
  6. body{   
  7.   margin: 0;   
  8.   padding: 0;    
  9. }  
  10. .div_alert_bg{   
  11.   width:100%;   
  12.   height:100%;   
  13.   position:fixed;   
  14.   left:0;   
  15.   top:0;   
  16.   z-index:2;  
  17.   opacity:0.3;   
  18.   background:#000;  
  19.   displaynone;   
  20. }  
  21. .div_loading{   
  22.   width:100%;   
  23.   height:100%;   
  24.   position:fixed;   
  25.   left:0;   
  26.   top:0;   
  27.   z-index:3;   
  28.   display:none;   
  29. }  
  30. .div_loading_img{   
  31.   top: 50%;  
  32.   left: 50%;  
  33.   positionabsolute;  
  34.   transform: translate(-50%, -50%);  
  35.   width:124px;  
  36.   
  37. }  
  38. .div_content{  
  39.   width:100%;   
  40.   height:100%;   
  41.   position:fixed;   
  42.   left:0;   
  43.   top:0;   
  44.   z-index:1;   
  45. }  
  46. #submit{  
  47.   top: 50%;  
  48.   left: 50%;  
  49.   positionabsolute;  
  50.   transform: translate(-50%, -50%);  
  51.   background-color:#d8f3ff;  
  52.   border:2px solid rgba(25,86,151,0.5);  
  53.   color:#000;  
  54.   font-size:1.2rem;  
  55.   height:2rem;  
  56.   width: 8rem;  
  57.   border-radius:10px;  
  58. }  
  59. </style>  
  60. </head>  
  61. <body>  
  62.   <div class="div_alert_bg"></div>  
  63.   <div class="div_loading">  
  64.     <div class="div_loading_img">  
  65.       <img width="100%" src="http://wx.karlew.com/ajaxLoading/img/loading.gif">  
  66.     </div>  
  67.   </div>  
  68.   <div class="div_content">  
  69.     <input id="submit" type="button" value="提交请求">  
  70.   </div>  
  71. </body>  
  72. </html>  
  73. <script type="text/javascript" src="http://libs.useso.com/js/jquery/2.1.1/jquery.min.js"></script>  
  74. <script type="text/javascript">  
  75.   $(document).ready(function(){  
  76.     $("#submit").click(function(){  
  77.       $.ajax({  
  78.         type: "GET",  
  79.         url: 'ajaxTset.php',  
  80.         beforeSend: function () {  
  81.           $(".div_alert_bg").show()  
  82.           $(".div_loading").show()  
  83.         },  
  84.         success: function (msg){  
  85.           $(".div_loading").hide()  
  86.           $(".div_alert_bg").hide()  
  87.           alert(msg)  
  88.         }  
  89.       })  
  90.     })  
  91.   })  
  92. </script>  

 

还有ajaxTest.php,为了让这个过程更加明显,我设置了2秒延时:

  1. sleep(2);  
  2. echo "已成功提交";  

 

演示地址:http://wx.karlew.com/ajaxLoading/

欢迎留言