jQuery Ajax 事件

Ajax請求會產生若干不同的事件,我們可以訂閱這些事件並在其中處理我們的邏輯。在jQuery這裏有兩種Ajax事件:局部事件 和 全局事件。

局部事件就是在每次的Ajax請求時在方法內定義的,例如:

 $.ajax({
   beforeSend: function(){
     // Handle the beforeSend event
   },
   complete: function(){
     // Handle the complete event
   }
   // ...
 });

全局事件是每次的Ajax請求都會觸發的,它會向DOM中的所有元素廣播,在上面 getScript() 示例中加載的腳本就是全局Ajax事件。全局事件可以如下定義:

 $("#loading").bind("ajaxSend", function(){
   $(this).show();
 }).bind("ajaxComplete", function(){
   $(this).hide();
 });

或者:

 $("#loading").ajaxStart(function(){
   $(this).show();
 }); 

我們可以在特定的請求將全局事件禁用,只要設置下 global 選項就可以了:

 $.ajax({
   url: "test.html",
   global: false,// 禁用全局Ajax事件.// ...
 });

下面是jQuery官方給出的完整的Ajax事件列表:

  • ajaxStart (Global Event)
    This event is broadcast if an Ajax request is started and no other Ajax requests are currently running.

    • beforeSend (Local Event)
      This event, which is triggered before an Ajax request is started, allows you to modify the XMLHttpRequest object (setting additional headers, if need be.)

    • ajaxSend (Global Event)
      This global event is also triggered before the request is run.

    • success (Local Event)
      This event is only called if the request was successful (no errors from the server, no errors with the data).

    • ajaxSuccess (Global Event)
      This event is also only called if the request was successful.

    • error (Local Event)
      This event is only called if an error occurred with the request (you can never have both an error and a success callback with a request).

    • ajaxError (Global Event)
      This global event behaves the same as the local error event.

    • complete (Local Event)
      This event is called regardless of if the request was successful, or not. You will always receive a complete callback, even for synchronous requests.

    • ajaxComplete (Global Event)
      This event behaves the same as the complete event and will be triggered every time an Ajax request finishes.


  • ajaxStop (Global Event)
    This global event is triggered if there are no more Ajax requests being processed.

    具體的全局事件請參考API文檔。
    好了,下面開始說jQuery裏面功能最強的Ajax請求方法 $.ajax();


    jQuery.ajax( options ) : 通過 HTTP 請求加載遠程數據

    這個是jQuery 的底層 AJAX 實現。簡單易用的高層實現見 $.get, $.post 等。

    $.ajax() 返回其創建的 XMLHttpRequest 對象。大多數情況下你無需直接操作該對象,但特殊情況下可用於手動終止請求。

    注意: 如果你指定了 dataType 選項,請確保服務器返回正確的 MIME 信息,(如 xml 返回 "text/xml")。錯誤的 MIME 類型可能導致不可預知的錯誤。見 Specifying the Data Type for AJAX Requests
    當設置 datatype 類型爲 'script' 的時候,所有的遠程(不在同一個域中)POST請求都回轉換爲GET方式。

    $.ajax() 只有一個參數:參數 key/value 對象,包含各配置及回調函數信息。詳細參數選項見下。

    jQuery 1.2 中,您可以跨域加載 JSON 數據,使用時需將數據類型設置爲 JSONP。使用 JSONP 形式調用函數時,如 "myurl?callback=?" jQuery 將自動替換 ? 爲正確的函數名,以執行回調函數。數據類型設置爲 "jsonp" 時,jQuery 將自動調用回調函數。(這個我不是很懂)

    參數列表:

    參數名類型描述
    urlString(默認: 當前頁地址) 發送請求的地址。
    typeString(默認: "GET") 請求方式 ("POST" 或 "GET"), 默認爲 "GET"。注意:其它 HTTP 請求方法,如 PUT 和 DELETE 也可以使用,但僅部分瀏覽器支持。
    timeoutNumber設置請求超時時間(毫秒)。此設置將覆蓋全局設置。
    asyncBoolean(默認: true) 默認設置下,所有請求均爲異步請求。如果需要發送同步請求,請將此選項設置爲 false。注意,同步請求將鎖住瀏覽器,用戶其它操作必須等待請求完成纔可以執行。
    beforeSendFunction發送請求前可修改 XMLHttpRequest 對象的函數,如添加自定義 HTTP 頭。XMLHttpRequest 對象是唯一的參數。
    function (XMLHttpRequest) {
      this; // the options for this ajax request
    }
    cacheBoolean(默認: true) jQuery 1.2 新功能,設置爲 false 將不會從瀏覽器緩存中加載請求信息。
    completeFunction請求完成後回調函數 (請求成功或失敗時均調用)。參數: XMLHttpRequest 對象,成功信息字符串。
    function (XMLHttpRequest, textStatus) {
      this; // the options for this ajax request
    }
    contentTypeString(默認: "application/x-www-form-urlencoded") 發送信息至服務器時內容編碼類型。默認值適合大多數應用場合。
    dataObject,
    String
    發送到服務器的數據。將自動轉換爲請求字符串格式。GET 請求中將附加在 URL 後。查看 processData 選項說明以禁止此自動轉換。必須爲 Key/Value 格式。如果爲數組,jQuery 將自動爲不同值對應同一個名稱。如 {foo:["bar1", "bar2"]} 轉換爲 '&foo=bar1&foo=bar2'。
    dataTypeString

    預期服務器返回的數據類型。如果不指定,jQuery 將自動根據 HTTP 包 MIME 信息返回 responseXML 或 responseText,並作爲回調函數參數傳遞,可用值:

    "xml": 返回 XML 文檔,可用 jQuery 處理。

    "html": 返回純文本 HTML 信息;包含 script 元素。

    "script": 返回純文本 JavaScript 代碼。不會自動緩存結果。

    "json": 返回 JSON 數據 。

    "jsonp": JSONP 格式。使用 JSONP 形式調用函數時,如 "myurl?callback=?" jQuery 將自動替換 ? 爲正確的函數名,以執行回調函數。






    errorFunction(默認: 自動判斷 (xml 或 html)) 請求失敗時將調用此方法。這個方法有三個參數:XMLHttpRequest 對象,錯誤信息,(可能)捕獲的錯誤對象。
    function (XMLHttpRequest, textStatus, errorThrown) {
      // 通常情況下textStatus和errorThown只有其中一個有值 this; // the options for this ajax request
    }
    globalBoolean(默認: true) 是否觸發全局 AJAX 事件。設置爲 false 將不會觸發全局 AJAX 事件,如 ajaxStart 或 ajaxStop 。可用於控制不同的Ajax事件
    ifModifiedBoolean(默認: false) 僅在服務器數據改變時獲取新數據。使用 HTTP 包 Last-Modified 頭信息判斷。
    processDataBoolean(默認: true) 默認情況下,發送的數據將被轉換爲對象(技術上講並非字符串) 以配合默認內容類型 "application/x-www-form-urlencoded"。如果要發送 DOM 樹信息或其它不希望轉換的信息,請設置爲 false。
    successFunction請求成功後回調函數。這個方法有兩個參數:服務器返回數據,返回狀態
    function (data, textStatus) {
      // data could be xmlDoc, jsonObj, html, text, etc...this; // the options for this ajax request
    }

    這裏有幾個Ajax事件參數:beforeSend success complete ,error 。我們可以定義這些事件來很好的處理我們的每一次的Ajax請求。注意一下,這些Ajax事件裏面的this 都是指向Ajax請求的選項信息的(請參考說 get() 方法時的this的圖片)。
    請認真閱讀上面的參數列表,如果你要用jQuery來進行Ajax開發,那麼這些參數你都必需熟知的。

原文轉自:http://www.cnblogs.com/qleelulu/archive/2008/04/21/1163021.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章