2010-09-15 73 views
2

在我的网站上,我使用了一个长轮询jQuery ajax函数。此函数中的这个ajax调用有50秒超时,然后再次运行,等待服务器上的更改。检查ajax调用/ http连接是否为当前活动

但是,有时长轮询http连接停止。例如,当互联网连接关闭或客户端电脑在休眠或休眠后打开时发生这种情况。问题在于“完成”回调没有发生,$ .ajax()函数仍在等待超时,而http连接不再存在。

如果连接仍处于打开状态,如何检查jquery/javascript?

这是我的长轮询脚本:

function longPoller() { 

    $.ajax({ 
     type: "GET", 
     url: '/longpolltest2.php', 
     dataType: 'json', 
     async: true, 
     cache: false, 
     timeout:50000, /* Timeout in ms */ 

     success: function(data){ 

      alert('success'); 
     }, 
     error: function(XMLHttpRequest, textStatus, errorThrown){ 

      alert('error'); 
     }, 

     complete: function() { 

      alert('complete'); 
      longPoller(); // restart long poller request 
      } 

    }); 
} 

@jAndy,我已经更新了剧本,但我收到以下错误:

权限遭拒,http://domain.com为对象创建包装类UnnamedClass

function masterLongPollerDebugger() { 

    xhr = $.ajax({ 
     type: "GET", 
     url: '/longpolltest2.php', 
     dataType: 'json', 
     async: true, 
     cache: false, 
     timeout:50000, 

     success: function(data){ 

      alert('success'); 
     }, 
     error: function(XMLHttpRequest, textStatus, errorThrown){ 

      alert('error'); 
     }, 

     complete: function() { 

      alert('complete'); 
      masterLongPollerDebugger(); 
      } 

    }); 
} 


function ajaxRunning() { 

    xhr._onreadystatechange = xhr.onreadystatechange; // store a reference 

    xhr.onreadystatechange = function() 
    { // overwrite the handler 
     xhr._onreadystatechange(); // call the original stored handler 
     alert(xhr.readyState); 
     if (xhr.readyState === 3) 
      alert('Interactive'); 
    }; 
} 

回答

2

您需要检查XHR readyState 3(交互)模式。

longpolltest2.php应该发送某种"ping data"到您的客户端(例如间隔10秒)。在readyState 4被触发之前收到的数据被称为interactive,并且XMLHttpRequest将触发onreadystatechangereadyState被设置为3

这有一些限制。 IE < 8不支持它,8支持它通过XDomainRequest对象。某些其他浏览器在启动readyState 3之前可能需要“前奏”数据。

另一件值得一提的事情是:jQuery目前不支持interactive mode(很可能是因为它远远超出了兼容的跨浏览器)。

无论如何,有一点变通方法,问题:

var xhr = $.ajax(...); 

xhr._onreadystatechange = xhr.onreadystatechange; // store a reference 

xhr.onreadystatechange = function() { // overwrite the handler 
    xhr._onreadystatechange(); // call the original stored handler 
    if (xhr.readyState === 3) alert('Interactive'); 
}; 
+0

我已更新原始帖子以获取更多信息。我得到一个错误:**拒绝http://domain.com为UnnamedClass类的对象创建包装的权限** – koen 2010-09-15 10:33:08

0

尝试使用

$(document).ready(function(){ 
    SetInterval(function(){ longPoller() }, 50000); 
}); 
+0

这不是一个回答我的问题。我已删除的setInterval代码来减少混淆。 – koen 2010-09-15 09:16:03

0

你可以尝试这样的事:

(function checkAjax() { 
    setTimeout(function() { 
     if ($.active === 0) { 
      alert('Should restart long polling now :-)'); 
     } else { 
      checkAjax(); 
     } 
    }, 500); 
}());