Ajax轮询和长轮询

缺点:Ajax轮询需要服务器有很快的处理速度与快速响应。long poll需要很高的并发,体现在同时容纳请求的能力。

一、轮询是在浏览器客户端实现的:

如果从后端获取数据成功则停止请求。

<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>

服务端的实现:

//获取数据TODO:
//验证数据TODO:
 switch ($operate) {
            case 'XXX':
                //长连接是实现
                # 设置最大的执行时间
                ini_set('max_execution_time', '0');// 服务器一直执行
                while (true) {
                    $status =获取数据
                    if ($status) {
                        break;
                    }
                }
                return json_encode($result);
                break:
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容