Ajax重構通用代碼AjaxRequest.js

var net = new Object(); // 定義一個全局變量net
// 編寫構造函數
net.AjaxRequest = function(url, onload, onerror, method, params) {
this.req = null;
this.onload = onload;
this.onerror = (onerror) ? onerror : this.defaultError;
this.loadDate(url, method, params);
}
// 編寫用於初始化XMLHttpRequest對象並指定處理函數,最後發送HTTP請求的方法
net.AjaxRequest.prototype.loadDate = function(url, method, params) {
if (!method) {
method = "GET";
}
if (window.XMLHttpRequest) {
this.req = new XMLHttpRequest();
} else if (window.ActiveXObject) {
this.req = new ActiveXObject("Microsoft.XMLHTTP");
}
if (this.req) {
try {
var loader = this;
this.req.onreadystatechange = function() {
net.AjaxRequest.onReadyState.call(loader);
}
this.req.open(method, url, true);// 建立對服務器的調用
if (method == "POST") {// 如果提交方式爲POST
this.req.setRequestHeader("Content-Type",
"application/x-www-form-urlencoded"); // 設置請求頭
}
this.req.send(params); // 發送請求
} catch (err) {
this.onerror.call(this);
}
}
}


// 重構回調函數
net.AjaxRequest.onReadyState = function() {
var req = this.req;
var ready = req.readyState;
if (ready == 4) {// 請求完成
if (req.status == 200) {// 請求成功
this.onload.call(this);
} else {
this.onerror.call(this);
}
}
}
// 重構默認的錯誤處理函數
net.AjaxRequest.prototype.defaultError = function() {
alert("錯誤數據\n\n回調狀態:" + this.req.readyState + "\n狀態: " + this.req.status);
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章