简体   繁体   English

将全局回调添加到$ .ajaxSetup

[英]add global callback to $.ajaxSetup

I am use $.ajaxSetup to use a global authorization method, and global error handling in my site. 我使用$.ajaxSetup来使用全局授权方法,并在我的站点中使用全局错误处理。 I would like to pass a callback function into the global error method so I can call the function whenever I need to in the global error handler. 我想将回调函数传递给全局错误方法,这样我就可以在全局错误处理程序中随时调用该函数。 Here is my $.ajaxSetup : 这是我的$.ajaxSetup

    $.ajaxSetup({
       global: false,
       // type: "POST",
        beforeSend: function (xhr) {
            //The string needs to be turned into 'this.pasToken'
            //if not us, don't include
            if(app.cookieAuth)
                xhr.setRequestHeader("Authorization", _this.pasToken);
        },
        statusCode: {
            401: function(){
                //Redirect to the login window if the user is unauthorized
                window.location.href = app.loginUrl;
            },
            //This is where I need help
            403: function(error, callback){
                //Show an error message if permission isn't granted
                callback(error);
                alert(JSON.parse(error.responseText)['Message']);
            }
        }
     });

Note the 403: status code. 请注意403:状态代码。 I am trying to pass in a callback function, but I don't know how to do it from the individual ajax calls. 我试图传递一个回调函数,但我不知道如何从单独的ajax调用。 Anyone have an idea? 有人有想法吗?

The easiest solution; 最简单的解决方案; define your own property for ajax options. 为ajax选项定义自己的属性。

$.ajaxSetup({
    statusCode: {
        403: function(error, callback){
            this.callback403(error);
        }
    }
});

$.ajax({
    callback403: function () {}
});

Note, if you change the context option of the ajax request, this may not work. 请注意,如果更改ajax请求的context选项,则可能无效。

I am not sure if this is what you are looking for: 我不确定这是不是你要找的东西:

$.ajax({
    statusCode: {
       404: function() {
     alert("page not found");
    }
   }
   });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM