2013-04-08 36 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"); 
    } 
    } 
    });