2012-03-09 38 views
1

我已經構建了一個Web應用程序,它在很多不同的頁面上大量使用jQuery.ajax()函數。當然,每次使用jQuery.ajax()都會傳遞一個配置對象和一個函數作爲'success'屬性的回調函數。執行前攔截jQuery.ajax的'成功'回調函數

我現在遇到了一種情況,我希望全局在多個頁面上執行某個操作,如果服務器返回任何給定ajax請求的某個錯誤代碼。我想通過在我的頁面的頭部包含javascript來覆蓋jQuery庫的一部分,這會執行條件檢查操作,然後繼續執行配置對象中傳遞的任何回調函數。這可能嗎?我目前正在審查jQuery庫的來源,看看我能否做到這一點。

回答

3

我想你需要看看全局Ajax事件處理程序。

http://api.jquery.com/category/ajax/global-ajax-event-handlers/

+2

全局AJAX的事件處理程序成功後的回調(例如)被解僱。如果OP在實際成功被解僱之前想要做一些事情,他將無法使用全局事件處理程序來完成。 – 2013-04-09 23:37:34

2

在jQuery的1.5 +,您可以通過converters選項$.ajax做到這一點。通常情況下,轉換器只是將從Web服務器接收到的數據轉換成成功回調,但如果需要,您可以在其中運行其他代碼。

將此代碼放入嵌入在所有頁面上的js文件中。

$.ajaxSetup({ 
    // the converter option is a list of dataType-to-dataType conversion functions 
    // example: converters['text json'] is a function that accepts text and returns an object 
    // note: to redefine any single converter, you must redefine all of them 
    converters: { 
     "text json": function (text) { 
      // NOTE: this converter must return a parsed version of the json     
      var result = jQuery.parseJSON(text); 
      if (result.errorMessage) { 
       // catch the error message and alert 
       alert(result.errorMessage) 
      } 
      return result;    
     }, 
     "text html": true,   
     "* text": window.String, 
     "text xml": jQuery.parseXML 
    } 
}); 

完整的示例: http://jsfiddle.net/waltbosz/8a8fZ/

0

我結束了使用$.ajaxSetup覆蓋從全球的成功回調,像這樣:

$.ajaxSetup({ 
    beforeSend: function(xhr, options) { 
     var originalSuccess = options.success 
     options.success = function(data, textStatus, jqXhr) { 
      // trigger some sort of event here for interested listeners 
      originalSuccess.apply(this, arguments) 
     } 
    } 
})