自己寫了一個簡單的 AJAX 請求庫,沒有依賴 jQuery,程式碼比 jQuery 輕量許多,供大家參考使用。
var ajax = {
init: function () {
var xmlHttp = new XMLHttpRequest();
if (!window.XMLHttpRequest)
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
return xmlHttp;
},
call: function (opt) {
var xmlHttp = this.init();
xmlHttp.onreadystatechange = function () {
if (xmlHttp.readyState === 4) {
xmlHttp.status === 200 ?
opt.success(xmlHttp.responseText, xmlHttp.responseXML) :
opt.error(xmlHttp.responseText, xmlHttp.status);
}
}
opt.data = this.parseData(opt.data);
if (opt.method.toLowerCase() === 'get') {
opt.url = opt.url + "?" + opt.data;
opt.data = null;
}
xmlHttp.open(opt.method, opt.url, opt.async);
if (opt.method.toLowerCase() === 'post')
xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlHttp.send(opt.data);
},
parseData: function (data) {
if (typeof data == 'object') {
var str = '';
for (var i in data) {
str += "&" + i + "=" + encodeURIComponent(data[i]);
}
return str.length == 0 ? str : str.substring(1);
} else {
return data;
}
}
}
這個庫透過 init 建立 XMLHttpRequest 對象(並相容舊版 IE 的 ActiveX),call 負責發送請求並依狀態碼分流到 success 或 error 回呼,parseData 則把對象形式的參數序列化成查詢字符串。使用時傳入包含 url、method、async、data 及回呼函數的設定對象即可。