In ajax applications, a page usually sends multiple requests at the same time. If there is only one XMLHttpRequest object, the previous request is not completed, and the subsequent request will overwrite the previous one, if a new XMLHttpRequest object is created each time, it will also cause waste. The solution is to create an XMLHttpRequset Object pool. If there is an idle object in the pool, use this object. Otherwise, a new object will be created.
Below is a simple class I recently wrote:
* XMLHttpRequest Object Pool
*
* @ Author legend <legendsky@hotmail.com>
* @ Link: http://www.ugia.cn /? P = 85
* @ Copyright www.ugia.cn
*/
VarXMLHttp= {
_ ObjPool: [],
_ GetInstance: Function ()
{
For (varI=0;I<This._ ObjPool.Length;I++)
{
If (This._ ObjPool[I].ReadyState=0|This._ ObjPool[I].ReadyState=4)
{
ReturnThis._ ObjPool[I];
}
}
// The push method is not supported in IE5.
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<MSXML.Length;N++)
{
Try
{
VarObjXMLHttp= NewActiveXObject(MSXML[N]);
Break;
}
Catch(E)
{
}
}
}
// Some mozilla versions do not have the readyState attribute
If (ObjXMLHttp.ReadyState=Null)
{
ObjXMLHttp.ReadyState=0;
ObjXMLHttp.AddEventListener("Load", Function ()
{
ObjXMLHttp.ReadyState=4;
If (Typeof objXMLHttp.Onreadystatechange="Function")
{
ObjXMLHttp.Onreadystatechange();
}
},False);
}
ReturnObjXMLHttp;
},
// Send the request (method [post, get], address, Data, callback function)
SendReq: Function (Method,Url,Data,Callback)
{
VarObjXMLHttp=This._ GetInstance();
With(ObjXMLHttp)
{
Try
{
// Add random numbers to prevent caching
If (Url.IndexOf("? ")>0)
{
Url+ ="& Randnum ="+Math.Random();
}
Else
{
Url+ ="? Randnum ="+Math.Random();
}
Open(Method,Url,True);
// Set the Request Encoding Method
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);
}
}
}
};
Example:
<Script type="Text/javascript"Src="Xmlhttp. js"></Script>
<Script type = "text/javascript">
Function test (obj)
{
Alert (obj. statusText );
}
XMLHttp. sendReq ('get', 'HTTP: // www.ugia.cn/wp-data/test.htm', '', test );
XMLHttp. sendReq ('get', 'HTTP: // www.ugia.cn/wp-data/test.htm', '', test );
XMLHttp. sendReq ('get', 'HTTP: // www.ugia.cn/wp-data/test.htm', '', test );
XMLHttp. sendReq ('get', 'HTTP: // www.ugia.cn/wp-data/test.htm', '', test );
Alert ('pool length: '+ XMLHttp. _ objPool. length );
</Script>
Download xmlhttp. js in demo