Ajax輪詢請求


Ajax輪詢請求

 

什么是輪詢?

  輪詢(polling):客戶端按規定時間定時向服務端發送ajax請求,服務器接到請求后馬上返回響應信息並關閉連接。

  Ajax輪詢需要服務器有很快的處理速度與快速響應。

 

 

Ajax輪詢實現

 

Ajax輪詢原理

客戶端是按照規定時間(這個時間由你設定,此處默認為1秒)像服務端發送請求,前一次請求完成后,無論有無結果返回,一秒之后下一次請求又會發出。這就叫做Ajax輪詢。

 

<script>
$(function(){
    var code,status;
    function getResult(){
        var params = {
            code: code,
            operate: '什么操作TODO:',
        };
        $.ajax({
            type: 'POST',
            url: "請求地址TODO:",
            data: params, 
            success: function(response) {
                console.log('成功啦');
                //對成功數據的操作TODO:
                clearInterval(status);               
            },
            dataType: 'json',
            timeout: 30*1000,// 超時時間
            // 超時意味着出錯了
            error: function (error) {
              console.log('失敗啦');
            }

        });
   }

  });
//獲取code。如果code存在則調用輪詢來獲取數據
    if(code){
           status = setInterval(getResult, 1000);
      }
   
  </script>

setInterval()用法:

 function direct() {
        console.info( "time: ", ( new Date() ).getTime() );
    }
    function showlog() {
        setInterval(direct(), 1000);
    }
    function showlog_2() {
        setInterval( direct, 1000 );
    }
    function showlog_3() {
        setInterval( function () {
            direct();
        }, 1000 );
    }
    function showlog_4() {
        setInterval( "direct()", 1000 );
    }
    // showlog(); //=> 執行一次
    // showlog_2(); //=> 每隔 1000毫秒 執行一次
    // showlog_3(); //=> 每隔 1000毫秒 執行一次
    // showlog_4(); //=> 每隔 1000毫秒 執行一次

 

長輪詢

  ajax實現:在發送ajax后,服務器端會阻塞請求直到有數據傳遞或超時才返回。 客戶端JavaScript響應處理函數會在處理完服務器返回的信息后,再次發出請求,客戶端再次建立連接,周而復始

<script>
$(function() {
    //定義code
    var code;
    //獲取code  TODO:
    getStatusLong();
    //  長輪詢執行
    function getStatusLong()
    {
        var data = {
            operate: '操作TODO:',
            code: code,
        };
        $.ajax({
            type: 'post',
            url: url, 
            data: data, 
            success: function(response) {
                if (response.error == 0) {
                //成功的操作
                }
            },
            dataType: 'json',
            timeout: 10*1000,// 超時時間
            // 超時意味着出錯了
            error: function (error) {
                console.log(error);// timeout
                // 立即發出請求
                getOrderStatusLong();
            }

        });

    }
});
</script>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM