首页 / 脚本样式 / Ajax / 实现发送多个Ajax请求
实现发送多个Ajax请求2011-08-23大家知道IE只能一次发送一个Ajax请求,你是否尝试过在一个页面上用Ajax请求多次,虽然可以实现我们发现代码很乱我们来实现一个在页面呈现缓存的例子吧!//获取Dom
function $(id) { return document.getElementById(id); }
思路:我们把要加载的缓存放在一个集合中,再迭代集合实现所有的获取缓存请求var cache={page:"Index",id:"Courses",element:$("Courses")};
//page为加载的缓存页面 id缓存ID,element显示缓存的Dom对象
顺便插一句:这个例子用Jquery实现的了吗?可以尝试一下,呵呵,这几天好像跟Jquery有仇一样上面定义了缓存对象,下面的代码就创建一个请求Ajax的方法,我们称之为: AsyncRequestvar 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);
}