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);
}
Ajax重構通用代碼AjaxRequest.js
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章
jquery爲下拉框賦值
lpz283929516
2020-07-08 07:40:36
深度瞭解Ajax技術
欧阳呀
2020-06-16 03:29:53
使用 ASP.NET 製作一個音樂網站
lesileqin
2020-02-23 18:03:38
使用 ASP.NET 爲自己做一個相親網站
lesileqin
2020-02-23 18:03:38
ASP.NET Ajax的使用方法
lesileqin
2020-02-23 18:03:38
Ajax開發過程表單提交數據出現亂碼和解決辦法
iteye_4080
2020-02-22 16:14:50
自己寫的ajax封裝js類
iteye_4080
2020-02-22 16:14:50
ajax/dwr/struts實例開發
kang275284
2020-02-22 10:21:55
JSP中使用AJAX示例:分別將結果提交爲STRUTS,SERVLET,WEBWORK的不同操作方式
kang275284
2020-02-22 10:21:55
ajax/dwr/struts實例開發
kang275284
2020-02-22 10:21:55
用Ajax實現表格動態滾動
kang275284
2020-02-22 10:21:55
Ajax傳遞的數據包含特殊字符時的解決方法
leeezm
2020-02-22 07:31:00
xmlhtttp 三級練級動
ASPNETCHENGXU
2020-02-22 05:43:25
JavaScript中的函數
dshj
2020-02-21 13:06:26