先來看如何創建一個跨瀏覽器的 XHR 對象:
function xmlHttpR(){
var xmlhttp;
if(window.XMLHttpRequest){
xmlhttp=new XMLHttpRequest();
}
else{
try{xmlhttp=new ActiveXObject("Msxml2.XMLHTTP")}
catch(e){
try{xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");}
catch(e){return null;}
}
}
return xmlhttp;
這樣一來,基本就能得到一個能在各瀏覽器下正常工作的異步請求對象了。下面是一個簡單的 Ajax 應用示例,基於 XmlHttpRequest 對象完成:
var ajaxEl=new Object();
//ajaxEl 是自定義的命名空間;
ajaxEl.contentLoad=function(url){
//IE 浏覽器下,會啟用緩存,這裡 url 加入 date 字段就是為了防止 IE 使用緩存,當然也可以使用 Math.random() 產生和 getTime 類似的效果;
url+="?date="+new Date().getTime();
this.req=null;
this.url=url;
//這個回調函數就是在數據在頁面上的更新函數;
this.onload=function(){
//domEl 是 ID 為 #test 的 dom 元素;
var domEl=document.getElementById("test");
//除了用 responseText 屬性,也可以使用 responseXml 獲得一張數據表;
domEl.innerHTML=this.req.responseText;
}
this.Xmlhttp(url);
}
ajaxEl.contentLoad.prototype={
Xmlhttp:function(url){
if(window.XMLHttpRequest){
this.req=new XMLHttpRequest();
}
else{
try{this.req=new ActiveXObject("Msxml2.XMLHTTP")}
catch(e){
try{this.req=new ActiveXObject("Microsoft.XMLHTTP");}
catch(e){return null;}
}
}
}
if(this.req){
var xmlR=this;
this.req.onreadystatechange=function(){
if(xmlR.req.readyState===4){
xmlR.onload.call(xmlR);
}
}
this.req.open("GET",url,true);
this.req.send(null);
}
}
}
var xmlE=new ajaxEl.contentLoad("main.php");
main.php 裡我寫了一個比較簡單的示例:在頁面上顯示一個類似 "now! time is:05:18:10 am 2011" 這樣可以動態變化的時間。
echo "now! time is:".date("H:i:s a Y");
從整個流程不難看出,原生 Ajax 的關鍵在於三點:創建兼容的 XHR 對象、通過 onreadystatechange 監聽 readyState 是否達到 4,以及在完成後更新頁面內容。掌握了這套思路,再去看 jQuery 封裝的 $.ajax,就會明白它其實是在這套基礎流程上做了更友好的抽象。