每次寫 Ajax 都要重刻一遍 XHR 的建立與狀態判斷太浪費生命。這裡提供一個把細節收攏起來的請求類別,只要設定幾個屬性再呼叫 send() 就好。
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 && XMLObj.status == 200) {
ObJSelf.callback(XMLObj);
}
};
if (this.method == "POST") XMLObj.send(this.content);
else XMLObj.send(null);
};
}
作者:HotHeart(熱血心腸) https://www.xujiwei.cn/
建立方式:var ajaxobj = new AJax;,建立失敗會回傳 false。
屬性:
method:請求方式,字串,POST 或 GET,預設 POSTurl:請求網址,預設空async:是否非同步,預設 truecontent:請求內容,POST 時需設定,預設空callback:回呼函式,回應送達時被呼叫,參數為 XMLHttpRequest 物件本身,寫成 function mycallback(XMLobj)方法:send(),無參數,負責送出請求。
<script type="text/javascript" src="AJaxrequest.js"></script>
<script type="text/javascript">
var ajaxobj = new AJaxRequest(); // 建立物件
ajaxobj.method = "GET"; // 指定為 GET
ajaxobj.url = "default.asp"; // 目標網址
// 回呼函式,把回應內容寫到畫面上
ajaxobj.callback = function (XMLobj) {
document.write(XMLobj.responseText);
};
ajaxobj.send(); // 送出
</script>
這個封裝的精神是對的:把跨瀏覽器的建構邏輯集中一處,呼叫端只關心 method、url 與 callback。不過它有幾處值得補強。
第一,回呼只帶 XHR 物件,呼叫端得自己判斷狀態;若改為直接傳入 responseText,使用起來會更乾淨。第二,if (!this.async) return false; 等於不允許同步請求,這行判斷應該拿掉。第三,也是最重要的:每個 AJaxRequest 實例都各自持有自己的 XHR 物件,這是正確的設計;但 XMLObj 與 ObJSelf 都是閉包變數,實例之間不會互相干擾,這一點比全域變數的寫法安全得多,正是〈變數衝突處理〉那篇想解決的問題。
最後,回呼裡最好加上錯誤分支與逾時處理(ontimeout 或自行用 setTimeout 計時),否則網路斷線時使用者只會看到一片空白。