理解 XMLHttpRequest (XHR) 運作機制,有助於除錯、效能調優、以及在無庫環境下開發。現代專案建議直接使用 fetch 或 axios,但 XHR 仍是基石。
/**
* 通用 AJAX 封裝(支援 GET/POST、JSON、表單、超時、取消)
* @param {Object} opts - {url, method, data, headers, timeout, responseType, onProgress}
* @returns {Promise} resolve(response), reject(error)
*/
function ajax(opts) {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
const method = (opts.method || 'GET').toUpperCase();
const url = opts.url + (method === 'GET' && opts.data ? '?' + toQueryString(opts.data) : '');
const async = opts.async !== false;
xhr.open(method, url, async);
xhr.timeout = opts.timeout || 0; // 0 = 無限制
xhr.responseType = opts.responseType || 'text'; // 'json', 'blob', 'arraybuffer', 'document'
// 預設標頭
const headers = Object.assign({
'X-Requested-With': 'XMLHttpRequest'
}, opts.headers);
// POST 表單預設 Content-Type
if (method === 'POST' && !headers['Content-Type'] && !(opts.data instanceof FormData)) {
headers['Content-Type'] = 'application/x-www-form-urlencoded';
}
Object.entries(headers).forEach(([k, v]) => xhr.setRequestHeader(k, v));
// 進度事件(上傳/下載)
if (opts.onProgress) {
xhr.upload.onprogress = e => opts.onProgress(e, 'upload');
xhr.onprogress = e => opts.onProgress(e, 'download');
}
xhr.onload = function() {
if (xhr.status >= 200 && xhr.status < 300) {
let data = xhr.response;
if (xhr.responseType === 'json' && typeof data === 'string') {
try { data = JSON.parse(data); } catch (e) { /* ignore */ }
}
resolve(data);
} else {
reject(new Error(`HTTP ${xhr.status}: ${xhr.statusText}`));
}
};
xhr.onerror = () => reject(new Error('Network Error'));
xhr.ontimeout = () => reject(new Error('Timeout'));
xhr.onabort = () => reject(new Error('Aborted'));
// 發送資料
const body = method === 'GET' ? null : toBody(opts.data, headers['Content-Type']);
xhr.send(body);
});
}
// 輔助:物件轉 query string
function toQueryString(obj) {
return Object.entries(obj).map(([k, v]) => encodeURIComponent(k) + '=' + encodeURIComponent(v)).join('&');
}
// 輔助:依 Content-Type 序列化 body
function toBody(data, contentType) {
if (data == null) return null;
if (data instanceof FormData || data instanceof Blob || typeof data === 'string') return data;
if (contentType && contentType.includes('application/json')) return JSON.stringify(data);
return toQueryString(data);
}
ajax({ url: '/api/user', method: 'GET', data: { id: 123 } })
.then(user => console.log('用戶:', user))
.catch(err => console.error(err));
ajax({
url: '/api/login',
method: 'POST',
data: { username: 'admin', password: '123' }
}).then(res => {
if (res.token) localStorage.setItem('token', res.token);
});
const formData = new FormData();
formData.append('avatar', fileInput.files[0]);
formData.append('userId', 123);
ajax({
url: '/api/upload',
method: 'POST',
data: formData,
headers: { 'Content-Type': null }, // 讓瀏覽器自動帶 boundary
onProgress: (e, dir) => {
if (dir === 'upload' && e.lengthComputable) {
console.log(`上傳進度: ${Math.round(e.loaded / e.total * 100)}%`);
}
}
}).then(res => alert('上傳成功'));
async function fetchJson(url, options = {}) {
const res = await fetch(url, {
credentials: 'include', // 攜帶 Cookie
headers: { 'Content-Type': 'application/json', ...options.headers },
...options
});
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return res.json();
}
// 用法
fetchJson('/api/users', { method: 'POST', body: JSON.stringify({ name: 'Tom' }) })
.then(data => console.log(data))
.catch(console.error);
| 特性 | XMLHttpRequest | Fetch |
|---|---|---|
| API 風格 | 事件回調 | Promise / async-await |
| 請求取消 | xhr.abort() | AbortController |
| 進度事件 | 原生支援 | 需 ReadableStream 手動處理 |
| Cookie 自動攜帶 | 同源自動 | 需 credentials: 'include' |
| 舊瀏覽器支援 | IE6+ | 需 Polyfill |
Access-Control-Allow-Origin 或使用 Proxy。Content-Type: application/x-www-form-urlencoded,JSON 設 application/json。onload/onerror 釋放參考,避免閉包持有大物件。ajax() 或 fetch() 統一處理 Token、錯誤碼、Loading 狀態。