javascript JQuery 捕获任何 ajax 错误
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17989961/
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 catch any ajax error
提问by MR.ABC
i like to catch any ajax 401 Unauthorised
exception, but do no like to change all my ajax queries. Is there a way to change it for any $.ajax call like (overwrite any error
handler) ?
我喜欢捕捉任何 ajax401 Unauthorised
异常,但不喜欢更改我所有的 ajax 查询。有没有办法为任何 $.ajax 调用(如(覆盖任何error
处理程序))更改它?
回答by Arun P Johny
you can use the global ajax event handlers .ajaxError()
您可以使用全局 ajax 事件处理程序.ajaxError()
$( document ).ajaxError(function( event, jqxhr, settings, exception ) {
? ? if ( jqxhr.status== 401 ) {
? ? ? ? $( "div.log" ).text( "Triggered ajaxError handler." );
? ? }
});
回答by pala?н
You can do something like this:
你可以这样做:
$(function() {
$.ajaxSetup({
error: function(jqXHR, exception) {
if (jqXHR.status === 401) {
alert('HTTP Error 401 Unauthorized.');
} else {
alert('Uncaught Error.\n' + jqXHR.responseText);
}
}
});
});
This will catch error in any of your ajax
calls.
这将在您的任何ajax
调用中捕获错误。
回答by Kevin Bowersox
The $.ajaxSetup()
function will allow you to specify global options for Ajax calls. Be careful however as other calls to ajaxSetup()
will overwrite global options and specified local options to the ajax()
method will override global settings.
该$.ajaxSetup()
函数将允许您为 Ajax 调用指定全局选项。但是要小心,因为其他调用ajaxSetup()
将覆盖全局选项,并且该ajax()
方法的指定本地选项将覆盖全局设置。
回答by Dave Sag
To catch a 401
status code simply add
要捕获401
状态代码,只需添加
$.ajaxSetup({
statusCode: {
401: function(err){
console.log('Login Failed.', err.responseJSON);
// or whatever...
}
}
});
to your page somewhere before the AJAX call is fired.
在 AJAX 调用被触发之前的某个地方到您的页面。
回答by Jordi
Try using .ajaxError()
as a global method http://api.jquery.com/ajaxError/
尝试使用.ajaxError()
作为全局方法http://api.jquery.com/ajaxError/