雖然 jQuery $.ajax()、Axios、Fetch API 已極其成熟,但在以下場景仍需原生封裝:
XMLHttpRequest 底層運作,面試或除錯必備。/**
* 簡易 AJAX 類別
* @param {string} url - 請求網址
* @param {string} data - 查詢字串或表單資料
*/
function Ajax(url, data) {
this.url = url;
this.data = data;
// 簡易瀏覽器判斷
this.browser = (navigator.userAgent.indexOf("MSIE") > 0) ? "MSIE" : "other";
}
Ajax.prototype = {
// 共用建立 XHR 物件
_createXHR: function() {
if (this.browser === "MSIE") {
try { return new ActiveXObject("Msxml2.XMLHTTP"); }
catch(e) { return new ActiveXObject("Microsoft.XMLHTTP"); }
}
return new XMLHttpRequest();
},
// GET 請求(同步示範,實務建議非同步)
get: function() {
var xhr = this._createXHR();
xhr.open('GET', this.url + '?' + this.data, false); // false = 同步
xhr.send(null);
return xhr.responseText; // 同步下直接回傳
},
// POST 請求
post: function() {
var xhr = this._createXHR();
xhr.open('POST', this.url, false);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send(this.data);
return xhr.responseText;
}
};
window.onload = function() {
document.getElementById("btn").onclick = function() {
var page = document.getElementById("t").value;
var ajax = new Ajax("phpOOP/getPage.php", "page=" + page);
document.getElementById("box").innerHTML = ajax.get(); // 同步阻塞 UI,僅示範
};
};
範例使用 open(..., false) 同步模式,send() 會阻塞主執行緒直到回應完成。**實際專案嚴禁同步請求**(會凍結頁面),應改用非同步 + 回調/Promise:
get: function(callback) {
var xhr = this._createXHR();
xhr.open('GET', this.url + '?' + this.data, true); // true = 非同步
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
callback(xhr.responseText);
}
};
xhr.send(null);
}
onreadystatechange 內部 this 指向 xhr,若需存取外層 this.url 需用閉包變數 var self = this 或箭頭函數(ES6+)。
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded") 告知伺服器解析請求體格式,否則 $_POST 可能為空。
class HttpClient {
constructor(baseURL = '') { this.baseURL = baseURL; }
async request(url, options = {}) {
const response = await fetch(this.baseURL + url, {
headers: { 'Content-Type': 'application/json', ...options.headers },
...options
});
if (!response.ok) throw new Error(`HTTP ${response.status}`);
return response.json(); // 或 text(), blob()
}
get(url, params) {
const qs = new URLSearchParams(params).toString();
return this.request(url + (qs ? '?' + qs : ''));
}
post(url, data) {
return this.request(url, { method: 'POST', body: JSON.stringify(data) });
}
}
// 使用
const api = new HttpClient('/api');
api.get('/users', { page: 1 }).then(data => console.log(data));
從 XMLHttpRequest 手動封裝到 Fetch + Promise 再到 async/await 類別化,AJAX 封裝的演進反映了 JavaScript 非同步程式設計的成熟。理解底層原理有助於在無庫環境、舊瀏覽器相容、效能調優等場景做出正確選擇。