Javascript constructs an xmlhttp Object pool to reasonably create and use xmlhttp objects

Source: Internet
Author: User

If ajax technology is frequently used on the client, we have to create xmlhttp objects multiple times. Of course, as you know, we can improve the creation method, such as using global variables to cache an instance (client Singleton mode ?!), This is very effective for synchronous communication, but this method may cause problems for asynchronous communication, because there is no process congestion, the user may call the same xmlhttp instance again when the previous communication is not completed, so that the callback function of the previous call is not triggered, the previous call is overwritten (that is, the previous call failed ). Creating a pool that maintains the xmlhttp instance has obvious advantages. The most obvious advantage is that we do not create redundant objects, at the same time, operations will not occur again on the same xmlhttp instance being called.

Specific implementation ideas:
We use an array to store the created xmlhttp object instance, and each call retrieves an instance from the pool. The xmlhttp instance does not need to be disposed of after communication, because its readyState attribute can identify whether it is available. If there is no idle xmlhttp instance at the time, if the number of instances in the pool is smaller than the maximum number of instances, a new instance is created and put into the pool. The improved implementation code is as follows:
Copy codeThe Code is as follows:
// Encapsulate the MyAjaxObj class of XMLHTTP
Var MyAjaxObj = new Object ();
Var maxXmlHttpCount = 5; // a maximum of five xmlhttp objects exist

MyAjaxObj. reqList = []; // you can clear the items in it.

MyAjaxObj. getFreeObj = function (){
Var req = null;
Var len = this. reqList. length;
// Obtain from the current pool first
For (var I = 0; I <len; I ++ ){
If (this. reqList [I]) {
If (this. reqList [I]. readyState = 4 | this. reqList [I]. readyState = 0 ){
Req = this. reqList [I];
Break;
}
}
}
// If there are no idle objects, create them independently
If (req = null ){
If (this. reqList. length <maxXmlHttpCount ){
Req = getXmlHttp ();
This. reqList. push (req );
}
}
Return req;
}


// Create an XMLHTTP object that is compatible with different browsers
Function getXmlHttp (){
Var xmlHttp = false;
Var arrSignatures = ["MSXML2.XMLHTTP. 5.0", "MSXML2.XMLHTTP. 4.0 ",
"MSXML2.XMLHTTP. 3.0", "MSXML2.XMLHTTP ",
"Microsoft. XMLHTTP"];
For (var I = 0; I <arrSignatures. length; I ++ ){
Try {
XmlHttp = new ActiveXObject (arrSignatures [I]);
Return xmlHttp;
}
Catch (oError ){
XmlHttp = false; // ignore
}
}
// Throw new Error ("MSXML is not installed on your system .");
If (! XmlHttp & typeof XMLHttpRequest! = 'Undefined '){
XmlHttp = new XMLHttpRequest ();
}
Return xmlHttp;
}

/* Encapsulate the requests sent from XMLHTTP to the server
Url: Request Path to the server; method: Request method, that is, get/post; *** callback: when the server returns a successful result, called functions (similar to c # callback functions )***
Data: The data contained in the request to the server; urlencoded: whether the url is encoded; cached: whether to use the cache; callBackError; the function called when the server returns an error
*/
MyAjaxObj. send = function (url, method, callback, data, urlencoded, cached, callBackError ){
Var req = this. getFreeObj (); // instantiate an XMLHTTP instance from the pool or directly.

// Call when the XMLHTTP Request status changes (core processing function)
Req. onreadystatechange = function (){
// When the request has been loaded

If (req. readyState = 4 ){
// When the request is returned successfully
If (req. status = 200) {// or req. status <400
// When a successful callback function is defined, the callback function is successfully executed.
If (callback)
Callback (req, data );
}
// When the request returns an error

Else {
// When the failed callback function is defined, the execution of the failed callback function
If (callBackError)
CallBackError (req, data );
}

// With pool management, we can save the effort to release resources
// Try {
// Delete req;
// Req = null;
//}
// Catch (e ){
// Alert (e. message );
//}
}
}

// If the POST request is sent back to the sending server
If (method. toUpperCase () = "POST "){
Req. open ("POST", url, true );
// Whether the request needs to be cached (this item can be set only after req. open)
If (cached)
Req. setRequestHeader ("If-Modified-Since", "0 ");
// The request must be encoded.
If (urlencoded)
Req. setRequestHeader ('content-type', 'application/x-www-form-urlencoded ');
Req. send (data );
MyAjaxObj. reqList. push (req );
}
// GET request
Else {
Req. open ("GET", url, true );
// Whether the request needs to be cached
If (cached)
Req. setRequestHeader ("If-Modified-Since", "0 ");
Req. send (null );
MyAjaxObj. reqList. push (req );
}
Return req;
}

// Clear all XMLHTTP array elements and release resources
MyAjaxObj. clearReqList = function (){
Var len = MyAjaxObj. reqList. length;
For (var I = 0; I <len; I ++ ){
Var req = MyAjaxObj. reqList [I];
If (req ){
Try {
Delete req;
} Catch (e ){}
}
}
MyAjaxObj. reqList = [];
}

// Further encapsulate the code when XMLHTTP sends a request in POST Mode
// IsClear: whether to clear all elements of the XMLHTTP array. For the meanings of other parameters, see MyAjaxObj. send.
MyAjaxObj. sendPost = function (url, data, callback, isClear, isCached, callBackError ){
If (isClear ){
MyAjaxObj. clearReqList ();
}
MyAjaxObj. send (url, "POST", callback, data, true, isCached, callBackError); // the post method must be encoded.
}
// Further encapsulate the code when XMLHTTP sends a request in GET Mode
MyAjaxObj. sendGet = function (url, args, callback, isClear, isCached, callBackError ){
If (isClear)
MyAjaxObj. clearReqList ();
Return MyAjaxObj. send (url, "GET", callback, args, false, isCached, callBackError );
}

Last ps: When chatting with a buddy last weekend, I talked about xmlhttp objects in ajax applications. The buddy ms asked me how xmlhttp can communicate asynchronously. I did not think about it at the time because this object processes our request calls in an "Asynchronous" way (of course, it can be set to synchronous, but this is a nonsense ), the current request does not affect other operations. This answer is very "official" and clearly does not cover the nature of the question. Dude, do you need bs people for your eyes? For a moment, I think that every xmlhttp asynchronous request will trigger a callback function. The call of this callback function does not affect other operations. This method is "Asynchronous ". If we compare the asynchronous processing callback methods in c #, they are actually the same in principle. Haha, now I finally figured it out. It's so proud and so promising. I'm so excited when I think of it!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.