XMLHttpRequest 的使用······

來源:互聯網
上載者:User

標籤: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 的使用······

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.