Ajax 的門檻其實不高,真正的複雜度都在「跨瀏覽器相容」這件歷史遺留問題上。本文用一個最經典的例子——輸入數字後自動帶出對應資料——把整個流程走完。
Firefox、Safari、Opera 等瀏覽器可以直接用建構式:
var xmlHttp = new XMLHttpRequest();
但 IE 走的是 ActiveX 路線,而且不同版本名稱也不同,必須分層嘗試:
var xmlHttp = false;
try {
xmlHttp = new XMLHttpRequest();
} catch (trymicrosoft) {
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP"); // 較新版
} catch (othermicrosoft) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); // 較舊版
} catch (failed) {
xmlHttp = false;
}
}
}
if (!xmlHttp) {
alert("無法建立 XMLHttpRequest 物件!");
}
open() 的三個參數分別是方法、網址、是否非同步。第三個給 true 就是非同步——這也是 Ajax 那個「A」的由來。
function getInfo() {
var num = document.getElementById("num").value;
var url = "/ajax/1.php?n=" + escape(num);
xmlHttp.open("GET", url, true); // true 代表非同步
xmlHttp.onreadystatechange = updatePage; // 務必放在 send 之前
xmlHttp.send(null); // GET 的參數在 URL 上,這裡給 null
}
GET 請求把參數放在網址上通常比 send() 簡單,多個參數用 & 串接即可。要注意 onreadystatechange 一定要在 send() 之前指派,否則回呼永遠不會被觸發。
<input name="num" id="num" onblur="getInfo()" type="text" />
用 onblur 而不是 onclick,使用者把焦點移開的瞬間就會送出查詢,體驗更順。
function updatePage() {
if (xmlHttp.readyState == 4) { // 4 表示請求已完成
var response = xmlHttp.responseText;
document.getElementById("city").value = response;
}
}
readyState 共有 0 到 4 五種值,4 代表請求已送出且處理完畢;responseText 取得伺服器回傳的文字,接著就能塞進任何元素裡。
var xmlHttp = false;
try {
xmlHttp = new XMLHttpRequest();
} catch (trymicrosoft) {
try { xmlHttp = new ActiveXObject("Msxml2.XMLHTTP"); }
catch (othermicrosoft) {
try { xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); }
catch (failed) { xmlHttp = false; }
}
}
if (!xmlHttp) { alert("無法建立 XMLHttpRequest 物件!"); }
function getInfo() {
var num = document.getElementById("num").value;
var url = "/ajax/1.php?n=" + escape(num);
xmlHttp.open("GET", url, true);
xmlHttp.onreadystatechange = updatePage;
xmlHttp.send(null);
}
function updatePage() {
if (xmlhttp.readyState == 4) {
document.getElementById("city").value = xmlhttp.responseText;
}
}
寫法和平常沒有兩樣:接收參數、處理、輸出即可,例如 echo $city;。真正需要留意的是輸出的編碼與 Content-Type 要和方法一致,中文才不會變亂碼。剩下的 PHP 邏輯其實不屬於 Ajax 的範疇,把資料準備好丟出來就是它的全部任務。
這個例子對初學者很適合,因為它把 Ajax 的四個環節——建立物件、設定連線、送出請求、接收回應——一次講完,之後不管換成哪個後端語言,骨架都是這一套。