Jquery 检查ajax调用/http连接当前是否处于活动状态
在我的网站上,我使用了一个长轮询jquery ajax函数。此函数中的ajax调用有50秒的超时,然后再次运行,等待服务器上的更改 但是,有时长轮询http连接会停止。例如,当internet连接断开时,或者当客户端pc在睡眠或休眠后打开时,就会发生这种情况。问题是“完整”回调尚未出现,$.ajax()函数仍在等待超时,而http连接已不存在 如果连接仍然打开,如何使用jquery/javascript进行检查? 这是我的长轮询脚本:Jquery 检查ajax调用/http连接当前是否处于活动状态,jquery,ajax,Jquery,Ajax,在我的网站上,我使用了一个长轮询jquery ajax函数。此函数中的ajax调用有50秒的超时,然后再次运行,等待服务器上的更改 但是,有时长轮询http连接会停止。例如,当internet连接断开时,或者当客户端pc在睡眠或休眠后打开时,就会发生这种情况。问题是“完整”回调尚未出现,$.ajax()函数仍在等待超时,而http连接已不存在 如果连接仍然打开,如何使用jquery/javascript进行检查? 这是我的长轮询脚本: function longPoller() { $
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,我已更新了脚本,但收到以下错误:
为类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');
};
}
尝试使用
$(document).ready(function(){
SetInterval(function(){ longPoller() }, 50000);
});
您需要检查
XHR readyState 3
(交互)模式
longpolltest2.php
应该向您的客户端发送某种类型的“ping数据”
(例如,间隔10秒)。在启动readyState 4
之前收到的数据称为interactive
,XMLHttpRequest
将启动onreadystatechange
,并将readyState
设置为3
这有一些限制。IE你可以试试这样的东西:
(function checkAjax() {
setTimeout(function () {
if ($.active === 0) {
alert('Should restart long polling now :-)');
} else {
checkAjax();
}
}, 500);
}());
这不是我问题的答案。。。我删除了SetInterval代码以减少混淆。我更新了原始帖子以获取更多信息。我得到一个错误:为类UnnamedClass的对象创建包装器的权限被拒绝
(function checkAjax() {
setTimeout(function () {
if ($.active === 0) {
alert('Should restart long polling now :-)');
} else {
checkAjax();
}
}, 500);
}());