使用 Ajax 的第一步,是偵測客戶端瀏覽器的類型,再據此取得對應的請求物件。由於使用者所用的瀏覽器五花八門,請求物件自然也不盡相同:在 Firefox、Netscape、Safari、Opera 中是 XMLHttpRequest;而在 IE 中則是 Microsoft.XMLHTTP 或 Msxml2.XMLHTTP。
以下為取得請求物件的完整程式碼。initReq 函數先透過 onreadystatechange 指定處理回應的函數 handleResponse,接著開啟連線、發送請求:
/* Initialize a Request object that is already constructed */
function initReq(reqType,url,bool){
/* onreadystatechange監聽handleResponse函數。接下來就是打開連接,發送請求…… */
request.onreadystatechange=handleResponse;
request.open(reqType,url,bool);
request.send(null);
}
接著是負責建構 Request 物件的包裝函數 httpRequest(),其參數包含請求類型(GET 或 POST)、伺服器程式的 URL,以及是否以非同步方式送出:
/* Wrapper function for constructing a Request object.
Parameters:
reqType: The HTTP request type such as GET or POST.
url: The URL of the server program.
asynch: Whether to send the request asynchronously or not. */
function httpRequest(reqType,url,asynch){
//Mozilla-based browsers
if(window.XMLHttpRequest){ //如果是非IE浏覽器
request = new XMLHttpRequest(); //取得對象。
initReq(reqType,url,asynch);
} else if (window.ActiveXObject){ //如果是IE浏覽器
request=new ActiveXObject("Msxml2.XMLHTTP");
if (! request){
request=new ActiveXObject("Microsoft.XMLHTTP");
}
if(request){
initReq(reqType,url,asynch);
/* Unlikely to branch here, as IE users will be able to use either one of the
constructors*/
} else {
alert("Your browser does not permit the use "+
"of all of this application's features!");
}
} else {
alert("Your browser does not permit the use "+
"of all of this application's features!");
}
}
值得留意的是,handleResponse 函數是整個事件處理的核心。掌握了跨瀏覽器建立請求物件的技巧,就跨出了撰寫 Ajax 應用的關鍵一步。