每次寫 Ajax 都要重複建立物件、設定標頭、寫狀態判斷,很膩。把它包成一個函式,用物件傳參數,之後呼叫就只剩一行。這份程式碼適合初學者直接拿去用。
先準備資料與設定物件,再呼叫 ajax(option):
// POST 方式
var txt = escape(sender.value);
var data = "name=" + txt + "&pwd=" + txt;
var option = {
"url": "handler/Handler.ashx",
"action": "POST",
"callback": function(){
if(xmlHttp.readyState == 4){ // 伺服器已回應
if(xmlHttp.status == 200){ // 伺服器正確回應
alert(xmlHttp.responseText);
}
xmlHttp = null; // 回收資源
}
},
"data": data
};
ajax(option);
// GET 方式(參數直接接在網址後面,不需要 data)
var option = {
"url": "handler/Handler.ashx&name=" + txt + "&pwd=" + txt,
"action": "POST",
"callback": function(){
if(xmlHttp.readyState == 4){
if(xmlHttp.status == 200){
alert(xmlHttp.responseText);
}
xmlHttp = null;
}
}
};
ajax(option);
function ajax(option) {
createXMlHttpRequest(); // 建立 xmlHttpRequest 物件
if(option != null && option != undefined){
if(option.url == null || option.url == undefined){
xmlHttp = null;
alert("缺少必要參數 option.url");
return;
}
if(option.action == null || option.action == undefined){
xmlHttp = null;
alert("缺少必要參數 option.action");
return;
}
xmlHttp.open(option.action, option.url, true);
if(option.contentType != null && option.contentType != undefined){
xmlHttp.setRequestHeader("Content-Type", option.contentType);
}else{
xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
}
if(option.callback != null && option.callback != undefined){
xmlHttp.onreadystatechange = option.callback;
}
if(option.action.toUpperCase() == "POST"){
xmlHttp.send(option.data); // POST 要送資料
}else{
xmlHttp.send(null); // GET 不送
}
}
}
var xmlHttp; // 呼叫完成後最好回收一下:xmlHttp = null;
/* 取得元素 */
function g(arg) {
var t = document.getElementById(arg);
if(null != t && t != undefined){ return t; }
t = document.getElementsByName(arg);
if(null != t && t != undefined){ return t; }
t = document.getElementsByTagName(arg);
if(null != t && t != undefined){ return t; }
}
/* 建立 ajax 請求物件 */
function createXMlHttpRequest() {
try { // Firefox, Chrome, Safari, Opera 8+
xmlHttp = new XMLHttpRequest();
}catch(ie){
try { // IE6+
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
}catch(ie){
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlHttp;
}
把「請求方式、網址、要送的資料、成功後要做什麼」全部收進一個物件,呼叫端就不必再關心 XHR 的細節。contentType 給了預設值,callback 是選填,action 會自動判斷要不要送 data——這些都是讓呼叫端更省事的小設計。
這份程式有幾個地方值得優化成現代寫法:
xmlHttp 是全域變數,多個併發請求會互相覆蓋。改成函式內的區域變數、或透過閉包傳回,才是安全的做法。status == 200,建議加上 onerror 與逾時處理,並把非 200 的狀態碼交給呼叫端決定怎麼顯示。"handler/Handler.ashx&name=" 用了 & 開頭,第一個參數應該是 ?。建議用 URLSearchParams 組字串,避免自己處理分隔符號。encodeURIComponent 才能正確處理非 ASCII 字元。若是新專案,直接用 fetch 搭配 async/await 會比這份封裝簡潔得多;需要維護舊系統時,這個模式仍然是很好的起點。