function createXHR() {
var xhr;
// 現代瀏覽器(IE7+、Firefox、Chrome、Safari、Opera)
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
// 某些瀏覽器需強制指定 MIME 類型
if (xhr.overrideMimeType) {
xhr.overrideMimeType('text/xml');
}
}
// IE5/IE6 (ActiveXObject)
else if (window.ActiveXObject) {
try {
xhr = new ActiveXObject('Msxml2.XMLHTTP'); // 較新版 MSXML
} catch (e) {
try {
xhr = new ActiveXObject('Microsoft.XMLHTTP'); // 舊版
} catch (e) {}
}
}
if (!xhr) {
throw new Error('您的瀏覽器不支持 XMLHttpRequest');
}
return xhr;
}
// 使用
var xhr = createXHR();
xhr.open('GET', '/api/data', true);
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
console.log(xhr.responseText);
}
};
xhr.send();
XMLHttpRequest,回退 ActiveX。Msxml2.XMLHTTP (3.0/4.0/5.0/6.0) 優於 Microsoft.XMLHTTP。// 原生 Promise 風格,無需兼容代碼
fetch('/api/data')
.then(res => res.text())
.then(data => console.log(data))
.catch(err => console.error(err));
// 或 async/await
async function getData() {
try {
var res = await fetch('/api/data');
var text = await res.text();
console.log(text);
} catch (e) { console.error(e); }
}
項目中應封裝統一 request(options) 函數,內部自動選擇 fetch 或 XHR(針對 IE11 等舊環境),統一攔截器、錯誤處理、超時控制。