ajax调用有时会被chrome取消

时间:2017-06-21 10:44:15

标签: javascript jquery ajax google-chrome

我的ajax代码是

var auto_refresh = setInterval(function () {
    $.ajax({
            type: 'post',
            url: 'lib/nav.php',
            data: 'c=autchk',
            success: function (result) {
                $('#test-div').html(result);
            },
            error: function (jqXHR, textStatus, errorThrown) {
                // I don't know how to display error message
                console.log('Error: '+jqXHR+' '+textStatus+' '+errorThrown);
            }
        });
}, 9000);

有时会在达到超时之前取消请求。 在chrome日志中,已取消请求的状态已停止。然后我读了引导我这个

的解释
  

队列。浏览器在以下时间对请求进行排队:

     
      
  • 有更高优先级的请求。
  •   
  • 已有六个TCP   连接为此原点打开,这是限制。适用于   仅限HTTP / 1.0和HTTP / 1.1。
  •   
     

停滞。由于排队中描述的任何原因,请求可能会停止。

问题是因为那个还是别的什么?

编辑:

我在3个浏览器中测试代码

我没有在Microsoft Edge中看到任何已取消的请求。 Chrome中的内容比Firefox多。

1 个答案:

答案 0 :(得分:0)

所有浏览器对同一来源的并发调用都有限制,已经对它进行了很好的讨论:Max parallel http connections in a browser?

问题在于你是以错误的方式实现自动刷新, 您正在使用的是:Polling,您基本上是定期调用服务器,但有时可能会发生您已经有其他人正在调用的情况,这将导致取消。

轮询是一种非常古老的方法,您应该查看WebSocketServer Side Events,这绝对是处理服务器端更改并将其反映到UI中的最佳方法。

如果你不能实现它们,那么你可能需要Long Polling Strategy,这是一种古老但仍然有价值的方式。

这里有其他信息:What are Long-Polling, Websockets, Server-Sent Events (SSE) and Comet?

function auto_refresh(onSuccess, onError, onEnd, rate, times) {
  onSuccess = onSuccess || $.noop;
  onError = onError || $.noop;
  onEnd = onEnd || $.noop;
  
  rate = Number(rate) || 9000;
  times = Number(times) || Infinity
  
  function iteration() {
    return $
      .post('lib/nav.php', 'c=autchk')
      .then(onSuccess)
      .fail(onError)
      .always(function() {
        if(Number.isFinite(times)) {
          times -= 1;

          if(times <= 0) {
            return onEnd();
          }
        }

        return auto_refresh(onSuccess, onError, onEnd, rate, times);
      })
    ;
  }
  
  return window.setTimeout(iteration, rate);
}


auto_refresh(function(result) {
  return $('#test-div').html(result).promise();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

相关问题