问题 全局$ .ajaxSetup()的jQuery异常可能吗?


我使用以下内容来捕获未经授权的访问并强制登录:

$.ajaxSetup({
    statusCode: {
        401: function(){
            //do stuff
        }
    }
});

工作得很好......当我访问我的服务器(域)上的资源时,但现在我试图通过ajax调用来使用第三方API资源,并且他们的401也被它捕获。那么,我怎么可能:

  1. 重写上面的代码只能从我的域中捕获401,或者
  2. 使用上述代码的异常进行$ .ajax()调用(使用不同的错误处理程序)

非常感谢!


7465
2017-07-11 20:16


起源



答案:


通过实验,我发现了答案。 $ .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) {
    }
});

12
2017-07-12 13:41





在你的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;
            }
        }
    }
});

1
2017-07-12 14:03





来自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的那个方面来为你提供准确的代码。


0
2017-07-11 20:26



在你的功能中,尝试 console.log(arguments, this)。一个对象可能包含URL,因此您只能在URL上运行该功能。 - Rocket Hazmat


答案:


通过实验,我发现了答案。 $ .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) {
    }
});

12
2017-07-12 13:41





在你的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;
            }
        }
    }
});

1
2017-07-12 14:03





来自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的那个方面来为你提供准确的代码。


0
2017-07-11 20:26



在你的功能中,尝试 console.log(arguments, this)。一个对象可能包含URL,因此您只能在URL上运行该功能。 - Rocket Hazmat