【问题标题】:add global callback to $.ajaxSetup将全局回调添加到 $.ajaxSetup
【发布时间】:2013-04-08 14:02:15
【问题描述】:

我使用$.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 调用来做到这一点。有人有想法吗?

【问题讨论】:

    标签: javascript ajax jquery callback


    【解决方案1】:

    最简单的解决方案;为 ajax 选项定义您自己的属性。

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

    注意,如果您更改 ajax 请求的 context 选项,这可能不起作用。

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-03-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-03-11
        • 2021-05-16
        相关资源
        最近更新 更多