AJAX (Asynchronous JavaScript and XML) 非技術新發明,而是既有技術的組合:
XMLHttpRequest (XHR) 或 fetch(),不阻塞頁面。let xhr;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest(); // 標準瀏覽器
} else if (window.ActiveXObject) {
xhr = new ActiveXObject("MSXML2.XMLHTTP"); // IE5/6
}
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) { // 完成
if (xhr.status === 200) {
handleSuccess(xhr.responseText, xhr.responseXML);
} else if (xhr.status === 404) {
showError("資源不存在");
} else {
showError("伺服器錯誤: " + xhr.status);
}
} else {
// 可選:顯示載入中狀態 (readyState 1-3)
showLoading(xhr.readyState);
}
};
xhr.open("GET", "data.xml", true); // true = 異步
xhr.setRequestHeader("Accept", "application/xml"); // 可選
xhr.send(null); // GET 無請求主體
function handleSuccess(text, xmlDoc) {
if (!xmlDoc) return;
const root = xmlDoc.documentElement;
const header = root.getElementsByTagName('header')[0].firstChild.data;
document.getElementById('copy').innerHTML = header;
}
| 屬性/方法 | 說明 |
|---|---|
readyState | 0=未初始化, 1=載入中, 2=載入完成, 3=互動中, 4=完成 |
status | HTTP 狀態碼 (200, 404, 500...) |
responseText | 純文字回應 |
responseXML | 解析後的 Document 物件 |
open(method, url, async, user, pwd) | 初始化請求 |
send(body) | 發送請求 |
setRequestHeader(name, value) | 設定請求標頭 |
abort() | 取消請求 |
fetch('data.json')
.then(response => {
if (!response.ok) throw new Error(`HTTP ${response.status}`);
return response.json();
})
.then(data => {
document.getElementById('copy').textContent = data.header;
})
.catch(err => console.error('請求失敗:', err));
優點:Promise 鏈式調用、語法簡潔、支援 Stream、Service Worker 整合。
缺點:IE 不支援 (需 Polyfill)、無法直接取消請求 (需 AbortController)、預設不攜帶 Cookie (需 credentials: 'include')。
AJAX 變更頁面狀態不會產生歷史記錄。解決方案:
pushState()/replaceState() + popstate 事件。location.hash 變更 + hashchange 事件 (舊瀏覽器相容)。AJAX 核心價值在於提升使用者體驗的流暢度。技術選型應以「能否解決具體 UX 問題」為準,而非追逐新潮。現代開發建議直接使用 Fetch + Promise/async-await,搭配成熟前端框架處理路由與狀態管理。