XMLHttpRequest 物件(相容 IE6+)open(method, url, async) 開啟連線send() 發送請求onreadystatechange,readyState === 4 且 status === 200 時處理回應<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>AJAX 讀取 TXT</title>
</head>
<body>
<button id="btnLoad">請求資料</button>
<pre id="output" style="background:#f5f5f5;padding:10px;"></pre>
<script src="ajax.js"></script>
<script>
document.getElementById('btnLoad').onclick = function() {
Ajax('read.txt?' + Date.now(), function(text) {
document.getElementById('output').textContent = text;
}, function(err) {
alert('失敗: ' + err);
});
};
</script>
</body>
</html>
function Ajax(url, onSuccess, onError) {
var xhr;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest(); // IE7+, Firefox, Chrome, Safari, Opera
} else {
xhr = new ActiveXObject('Microsoft.XMLHTTP'); // IE6, IE5
}
xhr.open('GET', url, true); // 非同步
xhr.send(null);
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
onSuccess(xhr.responseText);
} else {
onError(xhr.status);
}
}
};
}
?t= + Date.now() 確保每次請求最新內容。onError,傳入 HTTP 狀態碼。file:// 協議無法跨域讀取,需架設本地伺服器(如 http-server、live-server、PHP/Node 靜態服務)。Content-Type: text/plain; charset=utf-8,否則中文可能亂碼。fetch('read.txt?' + Date.now())
.then(res => {
if (!res.ok) throw new Error('HTTP ' + res.status);
return res.text();
})
.then(text => document.getElementById('output').textContent = text)
.catch(err => alert('失敗: ' + err));
fetch 基於 Promise,語法更清晰,現代專案建議優先使用(配合 async/await)。