javascript對XMLHttpRequest異步請求的面向對象封裝
2024-09-01 08:29:20
供稿:網友
代碼如下:
function CallBackObject()
{
this.XmlHttp = this.GetHttpObject();
}
CallBackObject.prototype.GetHttpObject = function() //動態為CallBackObject的原型添加了GetHttpObject共有方法
{
//第一步:創建XMLHttpRequest對象
//進行兼容性判斷
var xmlhttp;
/*@cc_on
@if (@_jscript_version >= 5)
try {
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (E) {
xmlhttp = false;
}
}
@else
xmlhttp = false;
@end @*/
if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
try {
xmlhttp = new XMLHttpRequest();
} catch (e) {
xmlhttp = false;
}
}
return xmlhttp;
}
CallBackObject.prototype.DoCallBack = function(URL)
{
if( this.XmlHttp )
{
if( this.XmlHttp.readyState == 4 || this.XmlHttp.readyState == 0 )
{
var oThis = this;
//第二步:注冊回調方法,當服務器處理結束返回數據以后利用回調方法實現局部的頁面刷新數據
//這個回調方法實際上在每次XMLHttpRequest對象的readyState屬性的值發生變化的時候都會被調用
this.XmlHttp.onreadystatechange = function() {
//根據XmlHttp.readyState返回值不同調用不同的方法。
oThis.ReadyStateChange();
};
//第三步:設置和服務器交互的相應參數
this.XmlHttp.open('POST', URL);
this.XmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
//第四步:設置向服務器發送的數據,啟動和服務器端交互
this.XmlHttp.send(null);
}
}
}
CallBackObject.prototype.AbortCallBack = function()
{
if( this.XmlHttp )
this.XmlHttp.abort();
}
CallBackObject.prototype.ReadyStateChange = function() {
//第五步:判斷和服務器交互是否完成,還要判斷服務器端是否正確返回數據
//this.XmlHttp.readyState == 0初始化狀態。XMLHttpRequest 對象已創建或已被 abort() 方法重置。
if (this.XmlHttp.readyState == 1) {
//open() 方法已調用,但是 send() 方法未調用。請求還沒有被發送。
this.OnLoading();
}
else if (this.XmlHttp.readyState == 2) {
//Send() 方法已調用,HTTP 請求已發送到 Web 服務器。未接收到響應。
this.OnLoaded();
}
else if (this.XmlHttp.readyState == 3) {
//Receiving 所有響應頭部都已經接收到。響應體開始接收但未完成。
this.OnInteractive();
}
else if (this.XmlHttp.readyState == 4) {
//Loaded HTTP 響應已經完全接收。
if (this.XmlHttp.status == 0)
this.OnAbort();
else if (this.XmlHttp.status == 200 && this.XmlHttp.statusText == "OK")
this.OnComplete(this.XmlHttp.responseText, this.XmlHttp.responseXML);
else
this.OnError(this.XmlHttp.status, this.XmlHttp.statusText, this.XmlHttp.responseText);
}
}
CallBackObject.prototype.OnLoading = function()
{
// Loading