大家知道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的方法,我們稱之為: 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);
}