這個範例的價值在於註解寫得夠細,適合當作第一次接觸 XMLHttpRequest 的教材。以下把它的邏輯重新梳理一遍。
createXMLHttp() 負責建立物件,先試 Mozilla 的原生寫法,失敗再退到 IE 的 ActiveX,兩種 ActiveX 版本都試過後放棄:
var xmlHttp;
function createXMLHttp() {
if (window.XMLHttpRequest) {
xmlHttp = new XMLHttpRequest(); // Mozilla 系
} else if (window.ActiveXObject) {
try {
xmlHttp = new ActiveXObject('Msxml2.XMLHTTP');
} catch (e) {
try {
xmlHttp = new ActiveXObject('Microsoft.XMLHTTP');
} catch (e) { }
}
}
}
startXMLHttp() 是主流程:建立物件 → 收集表單值 → 編碼 → 設定回呼 → open → 設定標頭 → send。
function startXMLHttp() {
createXMLHttp();
var send_string = 'name=' + document.getElementById('name').value;
send_string = encodeURIComponent(send_string);
xmlHttp.onreadystatechange = dodo; // 狀態變化時觸發
xmlHttp.open('post', '1.asp', true); // 方式、網址、非同步
xmlHttp.setRequestHeader('cache-control', 'no-cache');
xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlHttp.send(send_string);
}
dodo() 是回呼,只處理「完成且成功」這一種狀態:
function dodo() {
if (xmlHttp.readyState !== 4) { return; } // 4 = 傳送完畢
if (xmlHttp.status !== 200) { return; } // 200 = OK,404 = 找不到
document.getElementById('content').innerHTML = xmlHttp.responseText;
}
readyState 與 status 這兩個判斷是 Ajax 的地基:前者表示請求在哪個階段,後者表示伺服器給了什麼結果。少了任何一個,錯誤狀態就會被當成正常值處理。
<%
Response.Expires = 0
Response.Expiresabsolute = Now() - 1
Response.AddHeader "pragma", "no-cache"
Response.AddHeader "cache-control", "private"
Response.CacheControl = "no-cache"
response.Charset = "GB2312" ' 回傳中文必須設定
Dim Content
Content = Request.Form("name")
Response.Write(Content)
%>
關閉快取這一段不能省。Ajax 以 GET 或相同參數重複請求時,瀏覽器與 IIS 都可能直接回快取內容,造成「改了資料畫面卻沒變」的假象。
HTML 部分很單純:一個用來放結果的 span(id 為 content)、一個觸發請求的按鈕、一個提供輸入值的文字框。按鈕的 onclick 呼叫 startXMLHttp,其餘交給 Ajax 完成。
它示範的是手寫 XMLHttpRequest 的做法,概念完全適用,但正式專案建議做三件事:把 createXMLHttp 抽成共用函數避免各頁重複、為請求加上 error 與 timeout 處理、以及把 innerHTML 的寫法改為 textContent(若內容含使用者輸入,用 innerHTML 會有 XSS 風險)。若環境允許,直接改用 fetch 會簡潔許多。