Ajax 不是新語言,而是一套「用既有標準做非同步溝通」的寫法。它讓網頁不必整頁重載,就能在背後跟伺服器要資料、送資料,使用者點一下之後畫面不必刷新,體感自然快得多。
XHR 提供了一組介面:送出請求、接收回應。整個生命週期可以拆成 open → send → 等待 readyState 變化 → 讀取回應。
var xhr = new XMLHttpRequest(); // 適用 IE7 以上與所有現代瀏覽器
open() 帶三個參數:請求方法(GET、POST…)、請求的 URL、是否非同步。要注意的是呼叫 open() 並不會真的送出請求,它只是把請求準備好。
xhr.open('get', 'index.jsp', false); // 最後一個 false 代表同步,實務上請用 true
send() 才是真正送出。它的參數是請求主體(body),沒有 body 時必須明確傳入 null,某些舊瀏覽器在省略參數時會出錯。
xhr.send(null);
回應回來後,資料會填進 XHR 的屬性:
200~299 代表成功,304 表示資源未變更、可直接使用瀏覽器快取,兩者都算「可用」:
xhr.open('get', 'index.jsp', false);
xhr.send(null);
if ((xhr.status >= 200 && xhr.status < 300) || xhr.status === 304) {
console.log(xhr.responseText);
} else {
console.log('請求失敗:' + xhr.status);
}
每次 readyState 改變都會觸發 readystatechange。實務上只有在 4 的時候才處理資料,而事件處理函式必須在 open() 之前掛上,否則可能漏掉早期階段(這是舊版瀏覽器常見的相容性陷阱)。
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if ((xhr.status >= 200 && xhr.status < 300) || xhr.status === 304) {
console.log(xhr.responseText);
} else {
console.log('請求失敗:' + xhr.status);
}
}
};
xhr.open('get', 'index.jsp', true);
xhr.send(null);
想在資料到齊前放棄,隨時可以中止:
xhr.abort();
送出 XHR 時,瀏覽器會自動帶上 Accept、Accept-Charset、Accept-Encoding、Accept-Language、Connection、Cookie、Host、Referer、User-Agent 等標頭。要加自訂標頭,用 setRequestHeader(),順序必須在 open() 之後、send() 之前:
xhr.open('get', 'index.jsp', true);
xhr.setRequestHeader('MyHeader', 'MyValue');
xhr.send(null);
讀取回應標頭則用 getResponseHeader('名稱');要一次拿全部,用 getAllResponseHeaders(),它會回傳一個包含所有標頭的長字串(需要自己拆行解析)。
var myHeader = xhr.getResponseHeader('MyHeader');
var allHeaders = xhr.getAllResponseHeaders();
GET 是查詢用,參數接在 URL 後面。每個參數的名稱與值都必須經過 encodeURIComponent() 編碼,否則遇到 &、=、空白或中文就會出錯:
xhr.open('get', 'login.jsp?name1=' + encodeURIComponent('value1')
+ '&name2=' + encodeURIComponent('value2'), true);
如果要把多個參數組裝得整齊一點,可以自己寫一個附加函式:
function addURLParam(url, name, value) {
url += (url.indexOf('?') === -1 ? '?' : '&');
url += encodeURIComponent(name) + '=' + encodeURIComponent(value);
return url;
}
var url = 'login.jsp';
url = addURLParam(url, 'username', 'xxyh');
url = addURLParam(url, 'password', 'xxyh123');
xhr.open('get', url, true);
POST 則用來送出需要被保存的資料,body 容量大、格式自由。最傳統的表單式提交要把 Content-Type 設為 application/x-www-form-urlencoded,body 是「key=value&key2=value2」的字串:
xhr.open('post', 'login.jsp', true);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
var form = document.getElementById('user-info');
xhr.send(serialize(form)); // serialize() 需自行實作或引用函式庫
而 serialize() 的精神其實很單純,就是把表單欄位 name/value 配對起來再編碼:
function serialize(form) {
var parts = [];
for (var i = 0; i < form.elements.length; i++) {
var el = form.elements[i];
if (!el.name || el.disabled) continue;
if ((el.type === 'checkbox' || el.type === 'radio') && !el.checked) continue;
parts.push(encodeURIComponent(el.name) + '=' + encodeURIComponent(el.value));
}
return parts.join('&');
}
若改成傳送 JSON,只要把 Content-Type 換成 application/json、body 用 JSON.stringify() 序列化,後端就能直接解析,這也是目前主流做法。
原生 XHR 的寫法繁瑣,因此 ES 之後有了 Fetch:
fetch('index.jsp')
.then(function (res) { return res.json(); })
.then(function (data) { console.log(data); })
.catch(function (err) { console.log(err.message); });
不過理解 XHR 仍然值得——它說明了狀態碼、標頭、非同步流程這些背後真正在發生的事,而 Fetch、axios、jQuery.ajax 全都是建立在同樣的基礎上。