現代瀏覽器 (IE7+, Firefox, Chrome, Safari, Opera) 皆支援原生 XMLHttpRequest;僅極舊版 IE (IE5/IE6) 需用 ActiveXObject。以下為通用工廠函數:
<script type="text/javascript">
function createXHR() {
var xhr;
try {
// 標準瀏覽器
xhr = new XMLHttpRequest();
} catch (e) {
// IE6 及以下
try {
xhr = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
alert("您的瀏覽器不支援 AJAX!");
return null;
}
}
}
return xhr;
}
// 使用範例
function ajaxDemo() {
var xmlHttp = createXHR();
if (!xmlHttp) return;
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
console.log("Response:", xmlHttp.responseText);
}
};
xmlHttp.open("GET", "api/data", true);
xmlHttp.send();
}
</script>
| 瀏覽器/版本 | 建立方式 |
|---|---|
| IE7+, Firefox 1+, Chrome, Safari, Opera 8+ | new XMLHttpRequest() |
| IE6, IE5 (MSXML 3.0+) | new ActiveXObject("Msxml2.XMLHTTP") |
| IE5 (MSXML 2.6) | new ActiveXObject("Microsoft.XMLHTTP") |
new XMLHttpRequest()** 或更推薦 fetch API。axios、superagent 等成熟庫,自動處理兼容、攔截器、取消、超時等。跨瀏覽器建立 XHR 的核心邏輯是「優先標準,回退 ActiveX」。隨著 IE 退出歷史舞台,這段兼容代碼已完成歷史使命,但理解其演進有助於欣賞現代 Web API 設計的便利性。