你沒有看錯標題,本文的確是在講Baidu ajax,不過是很久很久以前的版本了。
由於jQuery ajax 模組有800+行,而核心函數jQuery.ajax就有380+行,直接分析這段代碼很容易被代碼邏輯弄暈。
所以 我們先分析一段簡單的ajax代碼,來自早期的百度七巧板項目。
通過這個來先複習一遍ajax的知識。
baidu.ajax.request分離版
/** * 發送一個ajax請求 * @author: allstar, erik, berg * @name ajax.request * @function * @grammar ajax.request(url[, options]) * @param {string} url 發送請求的url * @param {Object} options 發送請求的選項參數 * @config {String} [method] 請求發送的類型。預設為GET * @config {Boolean} [async] 是否非同步請求。預設為true(非同步) * @config {String} [data] 需要發送的資料。如果是GET請求的話,不需要這個屬性 * @config {Object} [headers] 要設定的http request header * @config {number} [timeout] 逾時時間,單位ms * @config {String} [username] 使用者名稱 * @config {String} [password] 密碼 * @config {Function} [onsuccess] 請求成功時觸發,function(XMLHttpRequest xhr, string responseText)。 * @config {Function} [onfailure] 請求失敗時觸發,function(XMLHttpRequest xhr)。 * @config {Function} [onbeforerequest] 發送請求之前觸發,function(XMLHttpRequest xhr)。 * * @meta standard * @see ajax.get,ajax.post * * @returns {XMLHttpRequest} 發送請求的XMLHttpRequest對象 */var ajax = {};ajax.request = function(url,options,type){ // 是否需要非同步 var async = options.async||true, // 使用者名稱、密碼 username = options.username||"", password = options.password||"", // 需要傳輸的資料 data = options.data||"", // GET還是POST method = (options.method||"GET").toUpperCase(), // 要求標頭 headers = options.headers||{}, // 事件處理函數表 eventHandler = {}, // 請求資料類型 dataType = type||"string";//xml||string function stateChangeHandler(){ // 看看是否已經準備好了 if(xhr.readyState == 4){ // 得到xhr目前狀態 var sta = xhr.status; // 判斷是否成功 if(sta == 200||sta == 304){ // 成功則觸發成功 fire("success"); }else{ // 失敗則觸發失敗 fire("failure"); } // 清除綁定 window.setTimeout(function(){ xhr.onreadystatechange= new Function(); if (async){ xhr = null; } },0); } } function fire(type){ // 把type變成ontype type = "on"+type; // 在事件處理器表中找到對應事件的處理函數 var handler = eventHandler[type]; // 如果函數存在,則 if(handler){ // 不成功的話 if(type != "onsuccess"){ handler(xhr); // 成功了 }else{ // 則根據dataType返回不同的資料 handler(xhr,dataType!="xml"?xhr.responseText:xhr.responseXML); } } } // 組裝eventHandler for(var key in options){ eventHandler[key] = options[key]; } // 建立一個XMLHttpRequest對象 var xhr = new XMLHttpRequest(); // 如果方法是GET,則把資料群組裝到url中 if(method == "GET"){ url += (url.indexOf("?")>=0)?"&":"?"; url += data; // 清空data data = null; } // 如果是非同步 if (async){ // 綁定readystatechange的處理器 xhr.onreadystatechange = stateChangeHandler; } // 看看是否需要輸入密碼 if(username){ xhr.open(method,url,async,username,passowrd); }else{ xhr.open(method,url,async); } // 如果是POST if(method == "POST"){ // 設定一下要求標頭 xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); } // 把options中的要求標頭資訊全部設定進去 for(var key in headers){ xhr.setRequestHeader(name,headers[key]) } // 觸發事件beforerequest fire("beforerequest"); // 發送資料 xhr.send(data); // 如果不是非同步 if (!async){ // 則直接運行stateChangeHandler來處理資料 stateChangeHandler(); } return xhr;}