DIV CSS 佈局教程網

全面認識 jQuery 的 ajax 請求
編輯:JQuery特效代碼     

jQuery 對 ajax 做了大量封裝,提供了一系列便捷的方法,讓異步請求變得輕鬆。在正式深入之前,先梳理一下常用的 ajax 相關方法:

  • .ajaxComplete()——請求完成時觸發;
  • .ajaxError()——請求失敗時觸發;
  • .ajaxSend()——在 ajax 請求發送時執行;
  • .ajaxStart()——請求開始時;
  • .ajaxStop()——請求結束時;
  • .ajaxSuccess()——請求成功時;
  • .load()——從服務端加載數據並替換到選中的元素中;
  • jQuery.post()——使用 POST 請求加載服務端數據;
  • .serialize()——把表單元素編碼成字符串以便提交;
  • .serializeArray()——把表單元素編碼成鍵值對數組;
  • jQuery.param()——創建序列化後適用於 URL 或 ajax 請求的數據;
  • jQuery.getScript()——加載並執行一個 js 文件;
  • jQuery.getJSON()——加載 JSON 編碼的數據;
  • jQuery.get()——使用 GET 請求加載數據。

一、ajaxStart 與 ajaxStop

$(document).ready(function(){
  $('.log1').ajaxStart(function() {
    $(this).text('Triggered ajaxStart handler.');
  });
  $('.log2').ajaxStop(function() {
    $(this).text('Triggered ajaxStop handler.');
  });
  $('.trigger').click(function() {
    $('.result').load('xixi.html');
  });
});

上例中,class 為 result 的元素通過 load 加載了一個 xixi.html。執行順序是:先觸發 ajaxStart,再把 xixi.html 的內容加載到 result 元素中,最後觸發 ajaxStop。這組事件非常適合用來做全局的加載提示與狀態切換。

二、ajaxSend、ajaxComplete、ajaxSuccess 與 ajaxError

$(document).ready(function(){
  $('.log1').ajaxStart(function() { $(this).text('Triggered ajaxStart handler.'); });   //【1】
  $('.log2').ajaxStop(function() { $(this).text('Triggered ajaxStop handler.'); });     //【5】
  $('.result').ajaxSend(function() { $(this).text('Triggered ajaxSend handler.'); });   //【2】
  $('.result').ajaxComplete(function() { $(this).text('Triggered ajaxComplete handler.'); }); //【4】
  $('.result').ajaxSuccess(function() { $(this).text('Triggered ajaxSuccess handler.'); });   //【3】
  $(".result").ajaxError(function() { $(this).text("Triggered ajaxError handler."); });
  $('.trigger').click(function() {
    $('.result').load('xixi.html');
  });
});

從代碼中標註的序號可以清楚看到執行順序:ajaxStart → ajaxSend → ajaxSuccess → ajaxComplete → ajaxStop。而如果請求過程中出現錯誤(例如文件不存在),則會執行 ajaxError 中的方法而非 ajaxSuccess。

過去總覺得 ajax 的概念有些零亂,經過這番梳理後終於有了系統的認識。值得一提的是,請求採用的是 GET 還是 POST 方式,也是值得進一步研究的話題。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved