JavaScript constructs a XMLHTTP object pool to rationally create and use XMLHTTP objects _javascript techniques

Source: Internet
Author: User
If we use AJAX technology frequently on the client side, we have to create XMLHTTP objects multiple times. Of course, as you know, we can improve the way we create, such as using global variables to cache an instance (client-side singleton mode?!). ), for synchronous communication, this is useful, but this is a problem with asynchronous communication, because without a blockage of the process, the user may call the same XMLHTTP instance again when the last communication is not completed, so that the previous call is "overwritten" by a callback function that does not wait for the previous call to be fired. Dropped (also on behalf of the previous call failed). The benefit of creating a pool that maintains XMLHTTP instances is obvious, and the most obvious advantage is that we do not create redundant objects and do not appear to be manipulated again on the same XMLHTTP instance that is being invoked.

The concrete realization thought:
We use an array to store an instance of the XMLHTTP object that has been created, and then each call takes an instance from the pool. We do not have to do any disposal after the XMLHTTP instance is communicated, because its own readystate attribute can identify whether it is available, and if there is no idle XMLHTTP instance, and the number of instances in the pool is less than the maximum number of instances, create a new instance and put it into the pool. The revised implementation code is as follows:
Copy Code code as follows:

Myajaxobj class for encapsulating XMLHTTP
var myajaxobj = new Object ();
var maxxmlhttpcount = 5; Up to 5 XMLHTTP objects exist

Myajaxobj.reqlist = []; You can empty the items inside.

Myajaxobj.getfreeobj = function () {
var req = null;
var len = this.reqList.length;
First, take it from the current pool.
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 is no idle object, create yourself independently
if (req = = null) {
if (This.reqList.length < Maxxmlhttpcount) {
req = Getxmlhttp ();
This.reqList.push (req);
}
}
return req;
}


Create a 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 isn't installed on your system.");
if (!xmlhttp && typeof xmlhttprequest!= ' undefined ') {
XmlHttp = new XMLHttpRequest ();
}
return xmlHttp;
}

/* encapsulates XMLHTTP to send requested action to the server
URL: The path requested to the server; method: The requested approach, that is, Get/post;***callback: the function called when the server successfully returns results (similar to C # callback function) * * *
Data: Information that comes with the server when it is requested; Urlencoded:url is encoded; cached: whether to use caching; Callbackerror the function that is called when the server returns an error
*/
myajaxobj.send = function (URL, method, callback, data, urlencoded, cached, Callbackerror) {
var req = This.getfreeobj (); Instance of a XMLHTTP from the pool or directly instantiated

Called when the XMLHTTP request state changes (core handler function)
Req.onreadystatechange = function () {
When the request has been loaded

if (req.readystate = = 4) {
When the request returns success
if (Req.status = = 200) {//Req.status < 400
Execution of a successful callback function when a successful callback function is defined
if (callback)
Callback (req, data);
}
When the request returns an error

else {
Execution failure callback function when a failed callback function is defined
if (callbackerror)
Callbackerror (req, data);
}

There is a pooling of management, we can dispense with the method of releasing resources
try {
Delete req;
req = null;
// }
catch (e) {
alert (e.message);
// }
}
}

If you post back to the server
if (method.touppercase () = = "POST") {
Req.open ("POST", url, True);
Whether the request requires caching (this can only be set after Req.open)
if (cached)
Req.setrequestheader ("If-modified-since", "0");
Request requires encoding
if (urlencoded)
Req.setrequestheader (' Content-type ', ' application/x-www-form-urlencoded ');
Req.send (data);
MyAjaxObj.reqList.push (req);
}
Request in Get mode
else {
Req.open ("Get", url, True);
Whether the request requires caching
if (cached)
Req.setrequestheader ("If-modified-since", "0");
Req.send (NULL);
MyAjaxObj.reqList.push (req);
}
return req;
}

Clears all XMLHTTP array elements, releasing 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 encapsulates the code that XMLHTTP sends a request on post
Isclear: Whether to clear all elements of the XMLHTTP array; see the meaning of other parameters 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 requires encoding
}
Further encapsulates the code that XMLHTTP sends a request in Get mode
Myajaxobj.sendget = function (URL, args, callback, Isclear, iscached, Callbackerror) {
if (isclear)
Myajaxobj.clearreqlist ();
Return Myajaxobj.send (URLs, "get", callback, Args, false, iscached, callbackerror);
}

Finally PS: When chatting with a buddy last weekend, I talked about the XMLHTTP object in AJAX applications. That buddy Ms very "pious" asked me how XMLHTTP asynchronous communication. I didn't even think about it. Because this object handles our request call is "asynchronous" (of course it can be set to sync, but this is a nonsense), the current request does not affect other operations. The answer is "official", apparently without mentioning the nature of the problem. Dude, your eyes need to be so BS. Now a little analysis, the individual thought that in fact, each XMLHTTP asynchronous request will trigger a callback function, the call of the callback function does not affect other operations, this method is "asynchronous." If you compare the asynchronous processing callback methods in C #, they are actually interlinked in principle. Haha, now finally figured out, really too proud, too promising, think on the excitement!

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.