我使用以下内容来捕获未经授权的访问并强制登录:
$.ajaxSetup({
statusCode: {
401: function(){
//do stuff
}
}
});
工作得很好......当我访问我的服务器(域)上的资源时,但现在我试图通过ajax调用来使用第三方API资源,并且他们的401也被它捕获。那么,我怎么可能:
- 重写上面的代码只能从我的域中捕获401,或者
- 使用上述代码的异常进行$ .ajax()调用(使用不同的错误处理程序)
非常感谢!
通过实验,我发现了答案。 $ .ajaxSetup()基本上为任何$ .ajax()请求设置默认值。但是,可以为特定请求覆盖全局设置,如下所示:
$.ajaxSetup({
statusCode: {
401: function(){
//this will catch any and all access denied errors
}
}
});
$.ajax({
type: 'GET',
dataType: 'json',
url: someresouceurl,
statusCode: {
401: function(){
//except this one!
}
},
success: function(data) {
}
});
在你的401函数中扩展@MrOBrian的答案, this
设置为包含有关AJAX请求的信息的设置对象。其中一个属性是 url
。您可以阅读此内容,并检查它是否是您的URL。
$.ajaxSetup({
statusCode: {
401: function(){
var url = this.url;
if(url === myurl){ // check if url is yours
}
else{
// not your URL, do nothing
return;
}
}
}
});
来自jQuery API
If the request is successful, the status code functions take the same parameters as the success callback; if it results in an error, they take the same parameters as the error callback.
我建议你查看你得到的jqXHR参数,看看你是否可以将它缩小到你的域名,但是我不太了解jQuery的那个方面来为你提供准确的代码。
通过实验,我发现了答案。 $ .ajaxSetup()基本上为任何$ .ajax()请求设置默认值。但是,可以为特定请求覆盖全局设置,如下所示:
$.ajaxSetup({
statusCode: {
401: function(){
//this will catch any and all access denied errors
}
}
});
$.ajax({
type: 'GET',
dataType: 'json',
url: someresouceurl,
statusCode: {
401: function(){
//except this one!
}
},
success: function(data) {
}
});
在你的401函数中扩展@MrOBrian的答案, this
设置为包含有关AJAX请求的信息的设置对象。其中一个属性是 url
。您可以阅读此内容,并检查它是否是您的URL。
$.ajaxSetup({
statusCode: {
401: function(){
var url = this.url;
if(url === myurl){ // check if url is yours
}
else{
// not your URL, do nothing
return;
}
}
}
});
来自jQuery API
If the request is successful, the status code functions take the same parameters as the success callback; if it results in an error, they take the same parameters as the error callback.
我建议你查看你得到的jqXHR参数,看看你是否可以将它缩小到你的域名,但是我不太了解jQuery的那个方面来为你提供准确的代码。