2013-11-01 35 views
0

是否有可能判斷jQuery ajax請求是否持續了一定時間以上?我想提醒我的網站的用戶,如果請求已經持續10秒來重新加載並重試,但我無法在文檔中找到任何符合我的請求的內容。如何檢測jquery ajax請求是否已持續超過5秒

+0

@Murali設置短超時將使整個請求失敗。問題只是測量一個特定的請求正在運行的時間,而不是取消它 –

+0

https://developer.mozilla.org/en/docs/Web/API/window.setTimeout –

+0

你想讓這個只有一個ajax請求或任何ajax請求?作爲您網站上的「常見禮節」。 –

回答

1

設置超時,然後在ajax調用完成後取消它。

var timer = setTimeout(function() { 
    alert('Too long!'); 
}, 10000); 

$.getJSON(url, function() { 
    clearTimeout(timer); 
}); 
5

嘗試設置超時屬性並獲取錯誤處理程序參數。可能的值是

"timeout", "error", "abort", and "parsererror"

$.ajax({ 
    url: "/ajax_json_echo/", 
    type: "GET", 
    dataType: "json", 
    timeout: 1000, 
    success: function(response) { alert(response); }, 
    error: function(x, t, m) { 
     if(t==="timeout") { 
      alert("got timeout"); 
     } else { 
      alert(t); 
     } 
    } 
});​ 
2

所以對於網站中的所有Ajax請求......你應該做這樣的事情...

$.ajaxSetup({ 
    beforeSend: function(jqXHR, settings){ 

      /* Generate a timer for the request */ 
      jqXHR.timer = setTimeout(function(){ 

       /* Ask the user to confirm */ 
       if(confirm(settings.url + ' is taking too long. Cancel request?')){ 
        jqXHR.abort(); 
       } 
      }, 10000); 
    } 
}); 
+0

是把這個嗎? – ben

+0

只需確保它在加載頁面的請求時運行。像這樣$(function(){/ * paste code here * /}) –

+0

美麗的解決方案,謝謝! – tedwards947