javascript - $.ajax 超时示例错误且危险?

标签 javascript jquery ajax

当搜索“long-polling using jquery”时,这个link是最高的结果,我很惊讶为什么人们不关心他们所说的是否正确。

他们说:

Timeout: Set a timeout (in milliseconds) for the request. The timeout period starts at the point the $.ajax call is made. Here, we set the timeout to 30 seconds. This means our poll function won't get called again until both the ajax call is complete and (at-least) thirty (30) seconds have passed.

(强调我的)

但我想事实并非如此。

我测试了这段代码:

(function foo(){
    $.ajax({
        url:'/echo/json',
        success:function(d){
          console.log('Logged after 30secs');
        },
        timeout:30000,
        complete: foo
    });
})();

这是一个 fiddle证明强调的文字是错误的。

您可以看到 console.log() 在 30 秒之前被调用。

Both the setTimeout and setInterval techniques suffer from same flaw - a new connection to the server must be opened each time the $.ajax method is called. To make that connection, your realtime app must gear up and battle through hoards of competing network traffic to make it to your server.

有没有可靠的解决方案(除了套接字)可以使长轮询完美无缺?

最佳答案

等一下,jQuery ajax 方法的超时选项与长轮询无关。关于长轮询的文章是正确的。它在闭包中使用了 setTimeout。因为函数的下一次执行是在函数本身的内部,所以它保证了一次一个又一个地调用该函数。

然而,jQuery $.ajax 的超时选项允许指定取消调用的时间。即,如果服务器响应时间太长,只需取消请求即可。它与“长轮询”无关。

代码块应该是:

(function foo(){
    setTimeout(function(){
       $.ajax({
          url:'/echo/json',
          success:function(d){
            console.log('Logged after 30secs');
            foo()
          }
       });
    }, 30000);


})();

关于javascript - $.ajax 超时示例错误且危险?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24473566/

相关文章:

jquery - datatables 1.10 add.row() 在 ajax 响应中不起作用

javascript - ajax 请求后的 Chrome window.open 就像弹出窗口一样

javascript - 如何创建和组织 JavaScript 数组?

javascript - 如何在momentjs中显示带有当月和上个月月份名称的动态日期?

javascript - Rhino 性能和编译脚本

javascript - 从 Web 服务器运行 qooxdoo 源版本

javascript - 将输入文本的值绑定(bind)到按钮值jquery

jquery - yii2 activeform 同步ajax错误

javascript - django使用ajax从数据库检索数据并更新部分

javascript - 多字段 Elasticsearch 搜索