替 blog 加上無刷新搜尋與即時驗證之後,回頭檢視程式碼,會發現建立 XMLHttpRequest 的片段到處重複。既然這段邏輯重用性極高,不妨把它封裝成一個類別,之後呼叫起來就清爽多了。
這個 AJaxRequest 類別把請求相關的設定都變成屬性,讓使用者先設定再呼叫 send 即可,不必記住繁瑣的建立流程。
類別:AJaxRequest 建立:var ajaxobj = new AJaxRequest; // 建立失敗則回傳 false 屬性: method - 請求方法,POST 或 GET,預設 POST url - 請求 URL,字串,預設為空 async - 是否非同步,true 為非同步,false 為同步,預設 true content - 請求內容,POST 時需設定,預設為空 callback - 回呼函式,收到回應時呼叫,參數為 XMLHttpRequest 物件,例如 function mycallback(XMLobj) 方法: send - 發送請求,無參數
<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>
// 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);
}
}
封裝之後,无论是無刷新搜尋還是表單的即時驗證,都能用一致的寫法搞定,程式碼可讀性與 reuse 性都明顯提升。