最近做的一個項目中有需要使用Ajax的部分,正好不是很忙,所以自己寫了一個簡單的Ajax類,拿出來share一下:
function BmAjaxObject()
{
this.ajaxObj = this.getXmlHttpObject();
}
BmAjaxObject.prototype.getXmlHttpObject = function()
{
var _ajaxObj;
try
{
_ajaxObj = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e1)
{
try
{
_ajaxObj = new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e2)
{
_ajaxObj = false;
}
}
if(!_ajaxObj && typeof(XMLHttpRequest) != 'undefined')
{
_ajaxObj = new XMLHttpRequest();
}
return _ajaxObj;
}
BmAjaxObject.prototype.doCallBack = function(url)
{
if(this.ajaxObj)
{
this.ajaxObj.open('GET', url);
var othis = this;
this.ajaxObj.onreadystatechange = function() {othis.readyStateChange()};
this.ajaxObj.send(null);
}
}
BmAjaxObject.prototype.abortCallBack = function()
{
if(this.ajaxObj)
{
this.ajaxObj.abort();
}
}
BmAjaxObject.prototype.readyStateChange = function()
{
if(this.ajaxObj.readyState == 1)
{
this.onLoading();
}
else if(this.ajaxObj.readyState == 2)
{
this.onLoaded();
}
else if(this.ajaxObj.readyState == 3)
{
this.onInteractive();
}
else if(this.ajaxObj.readyState == 4)
{
if(this.ajaxObj.status == 0)
{
this.onAbort();
}
else if(this.ajaxObj.status == 200)
{
this.onComplete(this.ajaxObj.responseText, this.ajaxObj.responseXML);
}
else
{
this.onError(this.ajaxObj.status, this.ajaxObj.statusText, this.ajaxObj.responseText);
}
}
}
BmAjaxObject.prototype.onLoading = function() {}
BmAjaxObject.prototype.onLoaded = function() {}
BmAjaxObject.prototype.onInteractive = function() {}
BmAjaxObject.prototype.onComplete = function(responseText, responseXml) {}
BmAjaxObject.prototype.onError = function(status, statusText, responseText) {}
BmAjaxObject.prototype.onAbort = function() {}
使用方法:
var a = new BmAjaxObject();
a.doCallBack('DesignFacade');
a.onComplete = function(responseText, responseXml)
{
alert(responseText);
}
同樣,其他的方法可以使用相同的方式加上,項目中試用後,效果還可以。(裡邊用到了JS的類的概念)