雖然專案裡多半直接用 $.ajax,但理解底層的 XMLHttpRequest 依舊有價值 —— 畢竟 jQuery 只是幫我們抹平了各瀏覽器的差異。以下把原生寫法與封裝思路整理出來。
// 1. 建立異步物件
var xhr = new XMLHttpRequest();
// 2. 設定請求方法與網址,第三個參數 true 代表異步
xhr.open("post", url, true);
// 3. 設定表單編碼方式(POST 必備)
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
// 4. 註冊狀態變化回呼
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
alert(xhr.responseText);
}
}
// 5. 送出參數
xhr.send(params);
GET 請求常加上:
xhr.setRequestHeader("If-Modified-Since", "0");
目的是清除快取,確保每次都拿到最新資料。
POST 請求則需要:
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
這對應的是 <form method="post" enctype="..."> 中的編碼型別,三種常見值之一就是 application/x-www-form-urlencoded。
var ajaxHelp = {
// 建立異步物件
CreatXHR: function(){
return new XMLHttpRequest();
},
// GET 請求
AjaxGet: function(url, callBack){
this.AJAXCommon("get", url, null, callBack);
},
// POST 請求
AjaxPost: function(url, params, callBack){
this.AJAXCommon("post", url, params, callBack);
},
// 共用流程
AJAXCommon: function(method, url, params, callBack){
var xhr = this.CreatXHR();
xhr.open(method, url, true);
if (method == "get") {
xhr.setRequestHeader("If-Modified-Since", "0"); // 清除快取
} else {
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
}
xhr.onreadystatechange = function(){
if (xhr.readyState == 4 && xhr.status == 200) {
var datas = JSON.parse(xhr.responseText);
callBack(datas); // 執行回呼
}
};
xhr.send(params);
}
};
這樣一來,呼叫端只需 ajaxHelp.AjaxGet(url, fn) 或 ajaxHelp.AjaxPost(url, params, fn),不必每次重複那五個步驟。
補充一句:jQuery 裡的 $.ajax、$.get、$.post 本質上做的就是同一件事,只是額外處理了跨瀏覽器相容性與錯誤回呼等細節。理解底層之後,框架對你而言就不再是一個黑盒子。