需求很單純:點擊按鈕,透過 Ajax 讀取一個 txt 檔,再把內容彈跳出來。由於請求的是靜態文字檔,不必經過任何後端程式。
<script>
// 頁面載入完成後才綁定事件,避免取不到元素
window.onload = function () {
var oBtn = document.getElementById("btn");
oBtn.onclick = function () {
// 建立 XMLHttpRequest 物件
var xhr = new XMLHttpRequest();
// 以 GET 方式請求 1.txt,第三個參數 true 表示非同步
xhr.open("get", "1.txt", true);
// 掛上回呼函數(建議在 send 之前設定)
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
alert(xhr.responseText);
}
};
xhr.send();
};
};
</script>
<body>
<input type="button" value="按鈕" id="btn">
</body>
想把內容呈現在頁面上而非跳出提示,只要把 alert 換成 document.getElementById("area").innerHTML = xhr.responseText; 即可。