標籤:ajax web與伺服器非同步互動 xmlhttprequest
// JavaScript Document
/*建立XMLHttpRequest對象
*這段代碼的核心分為三步:
1、建立一個變數 xmlHttp 來引用即將建立的 XMLHttpRequest 對象。
2、嘗試在 Microsoft 瀏覽器中建立該對象:
1)嘗試使用 Msxml2.XMLHTTP 對象建立它。
2)如果失敗,再嘗試 Microsoft.XMLHTTP 對象。
3、如果仍然沒有建立 xmlHttp,則以非 Microsoft 的方式建立該對象。
*/
function createXmlHttp(){
var xmlHttp = false;
try {
//在 Microsoft 瀏覽器上建立 XMLHttpRequest 對象
//如果使用較新版本的 Internet Explorer,則需要使用對象 Msxml2.XMLHTTP
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
//較老版本的 Internet Explorer 則使用 Microsoft.XMLHTTP
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e2) {
xmlHttp = false;
}
}
//在非 Microsoft 瀏覽器上建立 XMLHttpRequest 對象
if (!xmlHttp && typeof XMLHttpRequest != ‘undefined‘) {
xmlHttp = new XMLHttpRequest();
}
return xmlHttp;
}
/*發出請求:
在所有 Ajax 應用程式中基本都雷同的流程:
1、從 Web 表單中擷取需要的資料。
2、建立要串連的 URL。
3、開啟到伺服器的串連。
4、設定伺服器在完成後要啟動並執行函數。
5、發送請求。
*/
function callServer() {
// Get the city and state from the web form
var city = document.getElementById("city").value;
var state = document.getElementById("state").value;
// Only go on if there are values for both fields
if ((city == null) || (city == "")) return;
if ((state == null) || (state == "")) return;
// Build the URL to connect to
var url = "/scripts/getZipCode.php?city=" + escape(city) + "&state=" + escape(state);
// Open a connection to the server
xmlHttp.open("GET", url, true);
// Setup a function for the server to run when it‘s done
xmlHttp.onreadystatechange = updatePage;
// Send the request
xmlHttp.send(null);
}
/*xmlHttp的 onreadystatechange 屬性可以告訴伺服器在運行完成後做什麼。
因為代碼沒有等待伺服器,必須讓伺服器知道怎麼做以便您能作出響應。
在這個樣本中,如果伺服器處理完了請求,一個特殊的名為 updatePage() 的方法將被觸發。
需要特別注意的是該屬性在代碼中設定的位置 —— 它是在調用 send() 之前 設定的。
發送請求之前必須設定該屬性,這樣伺服器在回答完成請求之後才能查看該屬性
*/
function updatePage() {
if (request.readyState == 4)
if (request.status == 200)
alert("Server is done!");
else if (request.status == 404)
alert("Request URL does not exist");
else
alert("Error: status code is " + request.status);
}
XMLHttpRequest 的使用······