以下是一個以 XMLHttpRequest 為核心的異步請求實作,示範如何建立跨瀏覽器的請求物件、送出 GET 請求、在回呼中處理回應,並把結果寫回頁面。
<script>
// 宣告一個變數
var xmlHttpRequest = false;
// 建立 XMLHttpRequest 物件
function createXMLHttpRequest() {
if (window.XMLHttpRequest) { // Mozilla 等
xmlHttpRequest = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
try {
xmlHttpRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlHttpRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {}
}
}
}
// 發送請求
function send(url) {
createXMLHttpRequest();
xmlHttpRequest.open("GET", url, true);
xmlHttpRequest.onreadystatechange = proce; // 指定處理回應的函數
xmlHttpRequest.send(null); // 發送請求
}
function proce() {
if (xmlHttpRequest.readyState == 4) { // 物件狀態
if (xmlHttpRequest.status == 200) { // 資料成功返回,開始處理
var res = xmlHttpRequest.responseText;
document.getElementById("info").innerHTML = res;
} else {
window.alert("所請求的頁面有異常");
}
}
}
// 表單檢核
function check() {
var province = document.getElementById("state");
var pindex = province.selectedIndex;
var pValue = province.options[pindex].value;
if (pValue == "") {
alert("請選擇一個州別");
return false;
} else {
send('model.cfm?event=' + pValue);
}
}
</script>
<body> <table> <form action="login" method="post"> <tr> <td>姓名: <input id="name" type="text" name="name1" /><p> <input type="button" value="檢測!" onclick="check()" /> </td> <td align="left"> <select id="state" name="state"> <option value="866">Virginia</option> <option value="867">Georgia</option> <option value="865">California</option> </select> </td> </tr> </form> </table> <div> <span name="info" id="info" style="background:#eeffdd; padding-left:4px; padding-right:4px;"></span> </div> </body>
流程說明:createXMLHttpRequest() 依瀏覽器能力建立請求物件,優先嘗試原生 XMLHttpRequest,舊版 IE 則回退到 ActiveX;send(url) 以異步 GET 送出請求並掛上回呼函數;proce() 在 readyState 為 4 且 status 為 200 時取出 responseText,寫入 id 為 info 的區塊,否則提示請求異常。表單端的 check() 先確認使用者已選擇州別,再把選項值帶進查詢字串送出請求。