ajax輪詢請求實現源碼分享

來源:互聯網
上載者:User

標籤:

ajax輪詢請求狀態是ajax學習中非常重要的也是必須掌握的知識點,今天就和大家一起來分享一下這部分內容,一起來看看吧。 
    這裡要實現的功能是:通過掃碼公眾號帶參數的二維碼,來登入網站。 
    但很明顯,如果ajax不間斷的請求伺服器,這樣會加重伺服器的負荷,所以本例採用的是js的setInterval來周期性調用執行一個ajax函數來來向伺服器請求資料,但請求成功或者請求一定次數後還未成功時用clearinterval函數清空計時器。 

代碼和注釋如下:(後端採用thinkPHP實現,所以js代碼中含有一些thinkPHP的文法規則) 

<script type="text/javascript" src="__CSS__/bootstrap-3.3.5-dist/js/bootstrap.min.js"></script> 
<script type="text/javascript"> 
  var uid = "{$uid}"; 
  var i = 0; 
  var timer; 
  $().ready(function(){ 
    //開啟掃碼登入模態框 
    $(’#login’).click(function(){ 
      //如果使用者已經登入,則返回 
      if(uid){ 
        return ; 
      } 
      //開啟模態框,通過remote選項從遠程載入資料 
      $(’#loginModel’).modal({ 
        remote: "{:U(’user/login’)}" 
      }); 
    }); 
    
    //模態框隱藏之後清空資料 
    $("#loginModel").on("hidden.bs.modal", function() { 
        $(this).removeData("bs.modal"); 
    }); 
    
    //當模態框顯示出來後,通過定時返回來向伺服器請求資料,定時器是每三秒請求一次伺服器 
    $(’#loginModel’).on(’shown.bs.modal’, function (e) { 
      timer = setInterval(ajax_request, 3000); 
    }); 
  }); 
  
  //ajax 請求函數, 
  function ajax_request(){ 
    i++; 
    //如果已經請求20此沒有請求成功,則強制結束,給出提示資訊,因為每3s調用一次,供調用20次,大概就是一分鐘的時間 
    if(i > 20){ 
      $(’.login_info1’).html(’<span style="color:red;">登入逾時,如需登入請重新整理頁面~</span>’); 
      clearInterval(timer); 
      return ; 
    } 
    
    $.ajax({ 
      type: "post", 
      url: "{:U(’User/login_qrcode’)}", 
      timeout : 3000, 
      data: { "scene_id": $(’#scene_id’).val() }, 
      success: function (msg){ 
        if(1 == msg.status){ 
          $(’.login_info1’).html(’<span style="color:#0C9;">’+msg.info+’</span>’); 
          setTimeout(refresh, 3000); 
          return ; 
        } 
      }, 
      error: function(){ 
      } 
    }); 
  } 
  
  //重載頁面 
  function refresh(){ 
    location.reload(); 
  } 
</script> 


文章來源:unix8

ajax輪詢請求實現源碼分享

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.