gpt4 book ai didi

javascript - jQuery AJAX 在窗口卸载时触发错误回调 - 如何过滤掉卸载并只捕获真正的错误?

转载 作者:IT王子 更新时间:2023-10-29 03:22:07 24 4
gpt4 key购买 nike

如果我在 $.ajax() 请求中间离开页面,它会触发错误回调。我已经在 Safari 和 FF 中使用 GET 和 POST 请求进行了测试。

一个潜在的解决方案是在页面卸载时中止所有 AJAX 请求,但错误处理程序在卸载之前被调用,因此这似乎不可能。

我希望能够在客户端优雅地处理诸如 500s 之类的真实错误,使用礼貌的警告或模态对话框,但我不希望在用户离开页面时调用此处理。

我该怎么做?

--

(同样奇怪:离开页面时,错误处理程序说 textStatus 参数为“错误”,与收到 500/错误请求时抛出的相同。)

最佳答案

在错误回调或$.ajax你有三个输入参数:

function (XMLHttpRequest, textStatus, errorThrown) {
this; // options for this ajax request
}

可以直接查看xhr.status获取HTTP响应码,例如:

$.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 的评论):

On unload the xhr.readyState should be 0, where for a non responsive server the xhr.readyState should be 4.

关于javascript - jQuery AJAX 在窗口卸载时触发错误回调 - 如何过滤掉卸载并只捕获真正的错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1370322/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com