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 (VAR I = 0 ; I < This . _ Objpool . Length ; I ++)
{
If ( This . _ Objpool [ I ]. Readystate = 0 | This . _ Objpool [ I ]. Readystate = 4 )
{
Return This . _ 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
{
VaR MSXML = [ 'Msxml2. xmlhttp.5.0' , 'Msxml2. xmlhttp.4.0' , 'Msxml2. xmlhttp.3.0' , 'Msxml2. xmlhttp' , 'Microsoft. xmlhttp' ];
For (VAR N = 0 ; N < MSXML . Length ; N ++)
{
Try
{
VaR Objxmlhttp = New Activexobject ( 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 ()
{< br> 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 "
demo download XMLHTTP. JS