下面是我最近写的一个简单的类:
* XMLHttpRequest Object Pool
*
* @author legend
* @link http://www.ugia.cn/?p=85
* @Copyright www.ugia.cn
*/varXMLHttp= {_objPool: [],_getInstance: function ()
{
for (vari=0;i
{
if (this._objPool[i].readyState==0||this._objPool[i].readyState==4)
{
returnthis._objPool[i];
}
}// IE5中不支持push方法this._objPool[this._objPool.length] =this._createObj();
returnthis._objPool[this._objPool.length-1];
},_createObj: function ()
{
if (window.XMLHttpRequest)
{
varobjXMLHttp= newXMLHttpRequest();
}
else
{
varMSXML= ['MSXML2.XMLHTTP.5.0','MSXML2.XMLHTTP.4.0','MSXML2.XMLHTTP.3.0','MSXML2.XMLHTTP','Microsoft.XMLHTTP'];
for(varn=0;n
{try{
varobjXMLHttp= newActiveXObject(MSXML[n]);
break;
}catch(e)
{
}
}
}// mozilla某些版本没有readyState属性if (objXMLHttp.readyState==null)
{objXMLHttp.readyState=0;objXMLHttp.addEventListener("load", function ()
{objXMLHttp.readyState=4;
if (typeof objXMLHttp.onreadystatechange=="function")
{objXMLHttp.onreadystatechange();
}
},false);
}
returnobjXMLHttp;
},// 发送请求(方法[post,get], 地址, 数据, 回调函数)sendReq: function (method,url,data,callback)
{
varobjXMLHttp=this._getInstance();with(objXMLHttp)
{try{// 加随机数防止缓存if (url.indexOf("?") >0)
{url+="&randnum="+Math.random();
}
else
{url+="?randnum="+Math.random();
}open(method,url,true);// 设定请求编码方式setRequestHeader('Content-Type','application/x-www-form-urlencoded; charset=UTF-8');send(data);onreadystatechange= function ()
{
if (objXMLHttp.readyState==4&& (objXMLHttp.status==200||objXMLHttp.status==304))
{callback(objXMLHttp);
}
}
}catch(e)
{alert(e);
}
}
}
};