問題描述
如果我在 $.ajax() 請求中間離開頁面,它會觸發錯誤回調.我已經在 Safari 和 FF 中測試了 GET 和 POST 請求.
If I navigate away from a page in the middle of an $.ajax() request it fires the error callback. I've tested in Safari and FF with both GET and POST requests.
一種可能的解決方案是在頁面卸載時中止所有 AJAX 請求,但在卸載之前調用錯誤處理程序,因此這似乎是不可能的.
One potential solution would be to abort all AJAX requests on page unload, but the error handler is called before unload, so this doesn't seem possible.
我希望能夠通過禮貌警報或模式對話框在客戶端優雅地處理諸如 500 之類的真實錯誤,但我不希望在用戶離開頁面時調用此處理.
I want to be able to handle REAL errors such as 500s gracefully on the client side with a polite alert or a modal dialog, but I don't want this handling to be called when a user navigates away from the page.
我該怎么做?
--
(也很奇怪:當導航離開頁面時,錯誤處理程序說 textStatus 參數是錯誤",它在接收 500/bad 請求時拋出相同.)
(Also strange: When navigating away from a page, the error handler says that the textStatus parameter is "error", the same it throws when receiving a 500/bad request.)
推薦答案
在錯誤回調或$.ajax 你有三個輸入參數:
In the error callback or $.ajax you have three input arguments:
function (XMLHttpRequest, textStatus, errorThrown) {
this; // options for this ajax request
}
可以直接查看xhr.status
獲取HTTP響應碼,例如:
You can check directly the xhr.status
to get the HTTP response code, for example:
$.ajax({
url: "test.html",
cache: false,
success: function(html){
$("#results").append(html);
},
error: function (xhr, textStatus) {
if (xhr.status == 500) {
alert('Server error: '+ textStatus);
}
}
});
區分瀏覽器斷開的連接和服務器關閉的情況(jasonmerino 的評論):
To tell the difference between a connection broken by the browser and the case where the server is down (jasonmerino's comment):
卸載時 xhr.readyState 應為 0,其中表示無響應服務器的 xhr.readyState 應該是 4.
On unload the xhr.readyState should be 0, where for a non responsive server the xhr.readyState should be 4.
這篇關于jQuery AJAX 在窗口卸載時觸發錯誤回調 - 如何過濾掉卸載并只捕獲真正的錯誤?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!