jQuery.ajaxSetup:用 statusCode 覆盖错误
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8915393/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery.ajaxSetup: override error with statusCode
提问by weekens
I have the following code for default jQuery AJAX error handling:
我有以下用于默认 jQuery AJAX 错误处理的代码:
$.ajaxSetup({
error : function(jqXHR, textStatus, errorThrown) {
alert("Error: " + textStatus + ": " + errorThrown);
},
statusCode : {
404: function() {
alert("Element not found.");
}
}
});
However, when 404 happens, BOTH functions are upcalled: first error, then statusCode, so I see 2 consecutive alerts.
但是,当 404 发生时,两个函数都会被调用:首先是error,然后是statusCode,所以我看到了 2 个连续的警报。
How to prevent this behaviour and get errorcallback only if statusCodewas not upcalled?
仅当statusCode未被调用时,如何防止这种行为并获得错误回调?
回答by Garett
How about just checking for status code 404 in your error handler?
只检查错误处理程序中的状态代码 404 怎么样?
$.ajaxSetup({
error : function(jqXHR, textStatus, errorThrown) {
if (jqXHR.status == 404) {
alert("Element not found.");
} else {
alert("Error: " + textStatus + ": " + errorThrown);
}
}
});
回答by Bruce Hubbard
Try this:
尝试这个:
$.ajaxSetup({
error : function(jqXHR, textStatus, errorThrown) {
if(jqXHR.status === 404) {
alert("Element not found.");
} else {
alert("Error: " + textStatus + ": " + errorThrown);
}
}
});