首页 文章

ajax调用有时会被chrome取消

提问于
浏览
1

我的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 . 停滞不前 . 由于排队中描述的任何原因,请求可能会停止 .

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

EDIT :

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

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

1 回答

  • 0

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

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

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

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

    这里有其他信息: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>
    

相关问题