問(wèn)題描述
如果我在 $.ajax() 請(qǐng)求中間離開頁(yè)面,它會(huì)觸發(fā)錯(cuò)誤回調(diào).我已經(jīng)在 Safari 和 FF 中測(cè)試了 GET 和 POST 請(qǐng)求.
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.
一種可能的解決方案是在頁(yè)面卸載時(shí)中止所有 AJAX 請(qǐng)求,但在卸載之前調(diào)用錯(cuò)誤處理程序,因此這似乎是不可能的.
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.
我希望能夠通過(guò)禮貌警報(bào)或模式對(duì)話框在客戶端優(yōu)雅地處理諸如 500 之類的真實(shí)錯(cuò)誤,但我不希望在用戶離開頁(yè)面時(shí)調(diào)用此處理.
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.
我該怎么做?
--
(也很奇怪:當(dāng)導(dǎo)航離開頁(yè)面時(shí),錯(cuò)誤處理程序說(shuō) textStatus 參數(shù)是錯(cuò)誤",它在接收 500/bad 請(qǐng)求時(shí)拋出相同.)
(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.)
推薦答案
在錯(cuò)誤回調(diào)或$.ajax 你有三個(gè)輸入?yún)?shù):
In the error callback or $.ajax you have three input arguments:
function (XMLHttpRequest, textStatus, errorThrown) {
this; // options for this ajax request
}
可以直接查看xhr.status
獲取HTTP響應(yīng)碼,例如:
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);
}
}
});
區(qū)分瀏覽器斷開的連接和服務(wù)器關(guān)閉的情況(jasonmerino 的評(píng)論):
To tell the difference between a connection broken by the browser and the case where the server is down (jasonmerino's comment):
卸載時(shí) xhr.readyState 應(yīng)為 0,其中表示無(wú)響應(yīng)服務(wù)器的 xhr.readyState 應(yīng)該是 4.
On unload the xhr.readyState should be 0, where for a non responsive server the xhr.readyState should be 4.
這篇關(guān)于jQuery AJAX 在窗口卸載時(shí)觸發(fā)錯(cuò)誤回調(diào) - 如何過(guò)濾掉卸載并只捕獲真正的錯(cuò)誤?的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!