将全局回调函数添加到$.ajaxSetup

3

我正在使用$.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']);
            }
        }
     });

请注意 403 状态码。我试图传递一个回调函数,但是我不知道如何从单个的 ajax 调用中实现它。有人有想法吗?
2个回答

7
最简单的解决方案是:定义自己的属性来配置ajax选项。
$.ajaxSetup({
    statusCode: {
        403: function(error, callback){
            this.callback403(error);
        }
    }
});

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

请注意,如果您更改ajax请求的context选项,则可能无法正常工作。

-1

我不确定这是否是您正在寻找的内容:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接