每次寫 Ajax 都要重複一遍跨瀏覽器判斷與狀態檢查,實在繁瑣。把它包成一個類別,之後只要設定屬性、指定回呼函式、呼叫 send() 就好。
// AJAX 類
function AJAXRequest() {
var xmlObj = false;
var CBfunc, ObjSelf;
ObjSelf = this;
try { xmlObj = new XMLHttpRequest; }
catch(e) {
try { xmlObj = new ActiveXObject("MSXML2.XMLHTTP"); }
catch(e2) {
try { xmlObj = new ActiveXObject("Microsoft.XMLHTTP"); }
catch(e3) { xmlObj = false; }
}
}
if (!xmlObj) return false;
this.method = "POST";
this.url;
this.async = true;
this.content = "";
this.callback = function(cbobj) { return; }
this.send = function() {
if (!this.method || !this.url || !this.async) return false;
xmlObj.open(this.method, this.url, this.async);
if (this.method == "POST")
xmlObj.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlObj.onreadystatechange = function() {
if (xmlObj.readyState == 4) {
if (xmlObj.status == 200) {
ObjSelf.callback(xmlObj);
}
}
}
if (this.method == "POST") xmlObj.send(this.content);
else xmlObj.send(null);
}
}
作者:HotHeart(熱血心腸),網站 xujiwei.cn。
建立方式:var ajaxobj = new AJAX;,若建立失敗會回傳 false。
屬性:
method — 請求方法,字串,POST 或 GET,預設 POSTurl — 請求網址,字串,預設空值async — 是否非同步,true 為非同步、false 為同步,預設 truecontent — 請求內容,方法為 POST 時需設定,預設空值callback — 回呼函式,於收到回應時呼叫,預設直接返回。回呼函式有一個參數,即 XMLHttpRequest 物件,定義時寫成 function mycallback(xmlobj)方法:send() — 送出請求,無參數。
實作上使用 ObjSelf 保存 this 的參考,是因為 onreadystatechange 內的 this 會指向 XMLHttpRequest 而非類別執行個體;若直接寫 this.callback 就會取不到函式。
<script type="text/javascript" src="ajaxrequest.js"></script>
<script type="text/javascript">
var ajaxobj = new AJAXRequest; // 建立 AJAX 物件
ajaxobj.method = "GET"; // 設定請求方式為 GET
ajaxobj.url = "default.asp"; // URL 為 default.asp
// 設定回呼函式,輸出回應內容
ajaxobj.callback = function(xmlobj) {
document.write(xmlobj.responseText);
}
ajaxobj.send(); // 送出請求
</script>
這個封裝的優點是介面乾淨、意圖清楚;缺點是每個執行個體各自綁一份 XMLHttpRequest,且無法直接取用 responseXML——需要 XML 時得在回呼函式中自行從 xmlobj.responseXML 解析。若專案裡同時有多個並行請求,也建議把 xmlObj 收進每個執行個體各自的閉包中,避免相互干擾。