码迷,mamicode.com
首页 > Web开发 > 详细

Ajax轮询请求

时间:2019-06-05 23:40:57      阅读:167      评论:0      收藏:0      [点我收藏+]

标签:ESS   enter   long   ajax   阻塞   ext   center   发送请求   result   

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>

 

Ajax轮询请求

标签:ESS   enter   long   ajax   阻塞   ext   center   发送请求   result   

原文地址:https://www.cnblogs.com/-wenli/p/10982264.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!