Ajax(Asynchronous JavaScript and XML)的核心是 XMLHttpRequest (XHR) 物件,它讓瀏覽器能在不刷新頁面的情況下與伺服器異步通訊。本文從 XHR 物件創建、核心方法、跨瀏覽器兼容,到一個完整的 PHP + Ajax 交互範例,帶你快速上手。
現代瀏覽器(IE7+、Firefox、Chrome、Safari、Edge)均支持標準構造函數,僅 IE5/6 需 ActiveXObject。通用工廠函數如下:
function createXHR() {
if (window.XMLHttpRequest) {
return new XMLHttpRequest(); // 標準瀏覽器
} else if (window.ActiveXObject) {
// IE5/6 兼容
try {
return new ActiveXObject('Msxml2.XMLHTTP');
} catch (e) {
return new ActiveXObject('Microsoft.XMLHTTP');
}
}
throw new Error('XMLHttpRequest not supported');
}
| 方法/屬性 | 說明 |
|---|---|
open(method, url, async) | 初始化請求。method:GET/POST;async:true(異步)/false(同步) |
send(data) | 發送請求。GET 傳 null,POST 傳字串/FormData |
setRequestHeader(header, value) | 設置請求標頭(POST 必須設 Content-Type) |
onreadystatechange | 狀態變化事件處理器(回調函數) |
readyState | 狀態碼:0=未初始化, 1=載入中, 2=載入完成, 3=交互中, 4=完成 |
status | HTTP 狀態碼:200=成功, 404=未找到, 500=伺服器錯誤 |
responseText | 伺服器返回的文本響應體 |
responseXML | 解析為 XML Document 物件的響應體 |
var xhr = createXHR();
xhr.open('GET', 'api.php?id=123', true); // 異步
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) { // 請求完成
if (xhr.status === 200) { // HTTP 成功
console.log('響應:', xhr.responseText);
// 更新 DOM、解析 JSON 等
} else {
console.error('請求失敗:', xhr.status);
}
}
};
xhr.send(null);
<?php
// do.php
$id = isset($_GET['id']) ? intval($_GET['id']) : 0;
// 模擬處理:返回 id 重複 10 次
for ($i = 1; $i < 10; $i++) {
echo $id;
}
?>
// test.js
var xmlHttp;
function createXHR() {
if (window.ActiveXObject) {
xmlHttp = new ActiveXObject('Microsoft.XMLHTTP');
} else if (window.XMLHttpRequest) {
xmlHttp = new XMLHttpRequest();
}
}
function requestData(id) {
createXHR();
// GET 請求,參數拼接在 URL
xmlHttp.open("GET", "do.php?id=" + id, true);
xmlHttp.onreadystatechange = handleResponse;
xmlHttp.send(null);
}
function handleResponse() {
if (xmlHttp.readyState === 4 && xmlHttp.status === 200) {
var result = xmlHttp.responseText;
document.getElementById('resultContainer').innerHTML = result;
}
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Ajax Demo</title>
<script src="test.js" type="text/javascript"></script>
</head>
<body>
<a href="#" onclick="requestData(1); return false;">請求 ID=1</a> |
<a href="#" onclick="requestData(2); return false;">請求 ID=2</a> |
<a href="#" onclick="requestData(3); return false;">請求 ID=3</a>
<hr>
<div id="resultContainer" style="border:1px solid #ccc; padding:10px; min-height:50px;">
點擊上方鏈接查看異步加載結果...
</div>
</body>
</html>
// POST 發送 JSON
xhr.open('POST', 'api.php', true);
xhr.setRequestHeader('Content-Type', 'application/json;charset=UTF-8');
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
var data = JSON.parse(xhr.responseText); // 解析 JSON
// ...
}
};
xhr.send(JSON.stringify({ name: 'John', age: 30 }));
現代專案建議使用 fetch()(Promise 基礎,語法更優雅):
fetch('do.php?id=1')
.then(response => response.text())
.then(data => {
document.getElementById('resultContainer').innerHTML = data;
})
.catch(err => console.error(err));
但理解 XHR 原理對維護舊專案、處理特殊兼容性需求仍有價值。
XMLHttpRequest 創建、open/send/onreadystatechange 核心流程readyState===4 且 status===200fetch 或 axios,舊專案維護靈活運用 XHR