Implementation to send multiple AJAX requests

Source: Internet
Author: User

You know that IE can only send one Ajax request at a time, have you tried to request multiple times on a page with Ajax, although we can realize that the code is messy

Let's implement an example of a page rendering cache!

//获取Dom
function $(id) { return document.getElementById(id); }

Idea: We put the cache to be loaded in a set, and then iterate over the collection to implement all the cache requests

var cache={page:"Index",id:"Courses",element:$("Courses")};
//page为加载的缓存页面 id缓存ID,element显示缓存的Dom对象

By the way: Is this example implemented in jquery? Can try, hehe, these days seem to have a grudge with jquery

The cache object is defined above, and the following code creates a method to request Ajax, which we call: Asyncrequest

var xmlHttp = null;
function $AsyncRequest (request, callback) {
This.method = request.method!=null&&request.method.tolowercase () = = "Post"? " POST ":" Get ";
This.url = Request.url;
This.params = Request.params;
This.datatype =request.datatype!=null&&request.datatype.tolowercase () = = "xml"? "XML": "Text";
This.async = Request.async instanceof Boolean? Request.async:true;
if (callback!= null) {
this.success = callback.success;
This.error = Callback.error;
if (Callback.start!= null) Callback.start ();
}
if (xmlHttp = = null) {
if (window. XMLHttpRequest) xmlHttp = new XMLHttpRequest ();
else if (window. ActiveXObject) xmlhttp=new ActiveXObject ("MSXML2. XMLHTTP ") | | New ActiveXObject ("MICROSOFT. XMLHTTP ");
Else{return false;
}
var current = this;
Xmlhttp.open (This.method, This.url, This.async);
Xmlhttp.onreadystatechange = function () {
if (xmlhttp.readystate = = 4) {
if (Xmlhttp.status = = 200) {
if (current.success!= null)
Current.success (Current.datatype = = "xml"? xmlHttp.responseXml:xmlHttp.responseText);
}
else {
if (current.error!= null)
Current.error (Xmlhttp.responsetext);
}
}
}
if (this.method== "POST")
Xmlhttp.setrequestheader ("Content-type", "application/x-www-form-urlencoded");
Xmlhttp.send (This.params);
}

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.