2013-04-08 52 views
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调用中执行此操作。任何人有想法?

回答

7

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

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

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

注意,如果你改变了Ajax请求的context选项,这可能无法正常工作。

+0

正是我需要的。我会在几分钟内接受。 – coder 2013-04-08 14:12:13

-1

我不知道如果这是你在找什么:

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