Gra*_*ham 30 javascript ajax jquery xmlhttprequest
如果我离开$ .ajax()请求中间的页面,则会触发错误回调.我已经在Safari和FF中测试了GET和POST请求.
一个可能的解决方案是在页面卸载时中止所有AJAX请求,但是在卸载之前调用错误处理程序,所以这似乎不可能.
我希望能够通过礼貌警报或模态对话框在客户端优雅地处理诸如500s之类的REAL错误,但我不希望在用户离开页面时调用此处理.
我该怎么做呢?
-
(也很奇怪:当离开页面时,错误处理程序说textStatus参数是"错误",与接收500 /错误请求时抛出相同.)
CMS*_*CMS 24
在错误回调或$ .ajax中,您有三个输入参数:
function (XMLHttpRequest, textStatus, errorThrown) {
this; // options for this ajax request
}
Run Code Online (Sandbox Code Playgroud)
您可以直接检查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);
}
}
});
Run Code Online (Sandbox Code Playgroud)
编辑: 告诉浏览器断开的连接与服务器关闭的情况(jasonmerino的评论)之间的区别:
在卸载时,xhr.readyState应为0,对于非响应服务器,xhr.readyState应为4.
Leo*_*opd 12
在所有情况下都要正确处理这个问题.不幸的是,在许多流行的浏览器中,如果通过导航或服务器关闭/无响应取消AJAX调用,则xhr.status
相同(0
).所以这种技术很少奏效.
这是我积累的一组高度"实用"的黑客,它们在大多数情况下都能很好地工作,但仍然没有防弹.我们的想法是尝试捕获导航事件并设置一个在AJAX错误处理程序中检查的标志.像这样:
var global_is_navigating = false;
$(window).on('beforeunload',function() {
// Note: this event doesn't fire in mobile safari
global_is_navigating = true;
});
$("a").on('click',function() {
// Giant hack that can be helpful with mobile safari
if( $(this).attr('href') ) {
global_is_navigating = true;
}
});
$(document).ajaxError(function(evt, xhr, settings) {
// default AJAX error handler for page
if( global_is_navigating ) {
// AJAX call cancelled by navigation. Not a real error
return;
}
// process actual AJAX error here.
});
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
7844 次 |
最近记录: |