到處複製貼上 XMLHttpRequest 程式碼,很快就會難以維護。把建立物件、送出請求、狀態提示這幾件事收進一個類別裡,呼叫端就能簡化成一行。以下這個版本還多做了一件貼心的事:在頁面左下角顯示目前所處的連線階段。
new Ajax().Request(url, cmd, async, method, postString, title)
// Ajax 封裝 2007-3-13
function createXMLHttpRequest() {
try {
if (window.XMLHTTPRequest) {
return new XMLHttpRequest();
} else if (window.ActiveXObject) {
return new ActiveXObject("Microsoft.XMLHTTP");
}
} catch (e) {
alert("XMLHttpRequest對象無法創建!請檢查IE安全設置!");
}
}
// 在頁面左下角建立一列狀態提示
function messageDiv(t) {
var v = document.createElement("<div>");
v.innerHTML = "<table style=\"width:300px;\" id=message>" +
"<tr style=\"font-size:12px;background-color:#EEEEff;color:#227933;height:20px\">" +
"<td style=\"padding:2px;border-top:1px solid #E1E1E1;border-left:1px solid #E1E1E1;" +
"border-bottom:1px solid #818181;border-right:1px solid #A1A1A1\">" +
"<nobr><img src=refresh.gif align=absmiddle> " + t +
",<span id=Span1>連接未初始化...</span></nobr></td></tr></table>";
var l = document.getElementsByName("message").length;
v.style.cssText = "position:absolute;bottom:" + (l * 24) + "px;left:0px;display:none";
document.body.appendChild(v);
this.clear = function () {
document.body.removeChild(v);
var msg = document.getElementsByName("message");
for (var i = 0; i < msg.length; i++) {
msg[i].parentNode.style.cssText =
"position:absolute;bottom:" + (i * 24) + "px;left:0px";
}
};
this.showmsg = function (s) {
v.style.display = "";
v.all.Span1.innerHTML = s;
};
}
function Ajax() {
var x = new createXMLHttpRequest();
this.Request = function (url, cmd, async, method, postString, title) {
if (method != "post") method = "post"; else method = "get";
if (async != true) async = true; else async = false;
if (typeof (postString) != "string") postString = "";
if (typeof (title) != "string") title = "正在獲取數據"; else title = "正在獲取 " + title;
var msgbox = new messageDiv(title);
x.onreadystatechange = function () {
if (async) switch (x.readystate) {
case 1:
msgbox.showmsg("正在初始化連接..."); return;
case 2:
msgbox.showmsg("正在發送數據..."); return;
case 3:
msgbox.showmsg("正在接收數據..."); return;
case 4:
msgbox.showmsg("數據接收完成...");
if (x.status == 200) {
cmd(x.responseText);
msgbox.clear();
} else {
msgbox.showmsg("請求失敗," + x.statustext + "(" + x.status + ")");
setTimeout(msgbox.clear, 3000);
}
return;
}
};
x.open(method, url, async);
if (method == "post") { msgbox.showmsg("正在接收數據..."); x.send(postString); }
else x.send();
if (!async) {
msgbox.showmsg("數據接收完成...");
cmd(x.responseText);
msgbox.clear();
}
}
}
狀態提示列。messageDiv 每次建立時都會計算頁面上現有的提示列數量,用 l * 24 決定垂直位置,讓多個並行請求的提示不會重疊;clear() 移除自己之後,還會把其餘提示列重新往上疊。這個細節在同時發多個請求時相當實用。
同步/非同步雙軌。非同步模式下由 onreadystatechange 依 1~4 階段更新提示文字;同步模式下則在 send() 返回後直接呼叫回調,兩條路徑最終都收斂到同一個 cmd(responseText)。
三處值得修正的細節。其一,物件偵測寫成 window.XMLHTTPRequest(多了一個 Request),正確應為 window.XMLHttpRequest;其二,屬性名 readystate 與 statustext 應為駝峰式的 readyState 與 statusText,否則在部分瀏覽器上取不到值;其三,method 與 async 的判斷式邏輯寫反了(if (method != "post") method = "post" 會把所有非 post 都改成 post),應改為相等判斷。把這三處調整過後,這個類別就能穩定地在各瀏覽器上運作。