2010-09-15 29 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); 
}()); 
相關問題