Home  >  Article  >  Web Front-end  >  javascript builds an xmlhttp object pool to reasonably create and use xmlhttp objects_javascript skills

javascript builds an xmlhttp object pool to reasonably create and use xmlhttp objects_javascript skills

WBOY
WBOYOriginal
2016-05-16 18:36:16915browse

If we frequently use ajax technology on the client side, then we have to create xmlhttp objects multiple times. Of course, as you know, we can improve the way we create it, such as using global variables to cache an instance (singleton mode on the client?!). This is very effective for synchronous communication, but this method is not suitable for asynchronous communication. There will be problems with communication, because without the blocking of the process, the user may call the same xmlhttp instance again before the last communication is completed. In this way, the previous call will be "overwritten" before the callback function of the previous call is triggered ( This means that the previous call failed). The benefits of establishing a pool to hold xmlhttp instances are obvious. The most obvious advantage is that we will not create redundant objects, and at the same time, the same xmlhttp instance being called will not be operated again.

Specific implementation ideas:
We use an array to store the created xmlhttp object instances, and then fetch an instance from the pool each time it is called. After the communication of the xmlhttp instance is completed, we do not need to do any processing, because its own readyState attribute can identify whether it is available. If there is no idle xmlhttp instance at that time, and the number of instances in the pool is less than the maximum number of instances, then create a new one instance and put it into the pool. The re-improved implementation code is as follows:

Copy code The code is as follows:

//The MyAjaxObj class that encapsulates XMLHTTP
var MyAjaxObj = new Object();
var maxXmlHttpCount = 5; //Up to 5 xmlhttp objects exist

MyAjaxObj.reqList = []; //You can clear the items inside

MyAjaxObj.getFreeObj = function() {
var req = null;
var len = this.reqList.length;
//First Get
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 it independently
if (req == null) {
if (this.reqList.length < maxXmlHttpCount) {
req = getXmlHttp();
this .reqList.push(req);
}
}
return req;
}


//Create an XMLHTTP object, 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;
}

/* Encapsulates the operation of XMLHTTP sending a request to the server
url: the path to the server request; method: the request method, which is get/post; ***callback: when the server returns the result successfully , the function called (similar to c# callback function)***
data: the data attached when requesting the server; urlencoded: whether the url is encoded; cached: whether to use 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 from the pool or directly Instance of

//Called 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 returns success
if (req.status == 200) { //Or req.status < 400
// When success is defined When calling the function, execute the successful callback function
if (callback)
callback(req, data);
}
// When the request returns an error

else {
/ /When a failure callback function is defined, execute the failure callback function
if (callBackError)
callBackError(req, data);
}

// With pool management, we can save Methods to release resources
// try {
// delete req;
// req = null;
// }
// catch (e) {
// alert (e.message);
// }
}
}

//If sending back to the server in POST mode
if (method.toUpperCase() == "POST" ) {
req.open("POST", url, true);
//Whether the request needs to be cached (this can only be set after req.open)
if (cached)
req.setRequestHeader("If-Modified-Since", "0");
//The request needs to be encoded
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 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, 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 meaning 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 requires encoding
}
//Further encapsulates 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);
}

Finally PS: Last weekend when I was chatting with a buddy, I talked about the xmlhttp object in the ajax application. That buddy Ms. asked me very "devoutly" why xmlhttp communicates asynchronously. I said without thinking that because this object handles our request calls "asynchronously" (of course it can be set to synchronous, but this is nonsense), the current request will not affect other operations. This answer is very "official" and obviously does not address the essence of the problem. Brother, do you have to look so bs? Now after a little analysis, I personally think that each xmlhttp asynchronous request will trigger a callback function. The call of this callback function does not affect other operations. This method is "asynchronous". If you compare the asynchronous processing callback methods in C#, they are actually the same in principle. Haha, I finally figured it out now. I am so proud and promising. I get excited just thinking about it!
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn