XMLHttpRequest 對象
XMLHttpRequest 對象提供了在網頁加載后與服務器進行通信的方法。
什么是 XMLHttpRequest 對象?
XMLHttpRequest 對象是開發者的夢想,因為您能夠:
- 在不重新加載頁面的情況下更新網頁
- 在頁面已加載后從服務器請求數據
- 在頁面已加載后從服務器接收數據
- 在后臺向服務器發送數據
所有現代的瀏覽器都支持 XMLHttpRequest 對象。
創建 XMLHttpRequest 對象
通過一行簡單的 JavaScript 代碼,我們就可以創建 XMLHttpRequest 對象。
在所有現代瀏覽器中(包括 IE 7):
xmlhttp=new XMLHttpRequest()
在 Internet Explorer 5 和 6 中:
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP")
實例
<script type="text/javascript"> var xmlhttp; function loadXMLDoc(url) { xmlhttp=null; if (window.XMLHttpRequest) {// code for all new browsers xmlhttp=new XMLHttpRequest(); } else if (window.ActiveXObject) {// code for IE5 and IE6 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } if (xmlhttp!=null) { xmlhttp.onreadystatechange=state_Change; xmlhttp.open("GET",url,true); xmlhttp.send(null); } else { alert("Your browser does not support XMLHTTP."); } } function state_Change() { if (xmlhttp.readyState==4) {// 4 = "loaded" if (xmlhttp.status==200) {// 200 = OK // ...our code here... } else { alert("Problem retrieving XML data"); } } } </script>
注釋:onreadystatechange 是一個事件句柄。它的值 (state_Change) 是一個函數的名稱,當 XMLHttpRequest 對象的狀態發生改變時,會觸發此函數。狀態從 0 (uninitialized) 到 4 (complete) 進行變化。僅在狀態為 4 時,我們才執行代碼。
為什么使用 Async=true ?
我們的實例在 open() 的第三個參數中使用了 "true"。
該參數規定請求是否異步處理。
True 表示腳本會在 send() 方法之后繼續執行,而不等待來自服務器的響應。
onreadystatechange 事件使代碼復雜化了。但是這是在沒有得到服務器響應的情況下,防止代碼停止的最安全的方法。
通過把該參數設置為 "false",可以省去額外的 onreadystatechange 代碼。如果在請求失敗時是否執行其余的代碼無關緊要,那么可以使用這個參數。
XML / ASP
您也可以把 XML 文檔打開并發送到服務器上的 ASP 頁面,分析此請求,然后傳回結果。
<html> <body> <script type="text/javascript"> xmlHttp=null; if (window.XMLHttpRequest) {// code for IE7, Firefox, Opera, etc. xmlHttp=new XMLHttpRequest(); } else if (window.ActiveXObject) {// code for IE6, IE5 xmlHttp=new ActiveXObject("Microsoft.XMLHTTP"); } if (xmlHttp!=null) { xmlHttp.open("GET", "note.xml", false); xmlHttp.send(null); xmlDoc=xmlHttp.responseText; xmlHttp.open("POST", "demo_dom_http.asp", false); xmlHttp.send(xmlDoc); document.write(xmlHttp.responseText); } else { alert("Your browser does not support XMLHTTP."); } </script> </body> </html>
ASP 頁面,由 VBScript 編寫:
<% set xmldoc = Server.CreateObject("Microsoft.XMLDOM") xmldoc.async=false xmldoc.load(request) for each x in xmldoc.documentElement.childNodes if x.NodeName = "to" then name=x.text next response.write(name) %>
通過使用 response.write 屬性把結果傳回客戶端。
XMLHttpRequest 對象是 W3C 的標準嗎?
任何 W3C 推薦標準均未規定 XMLHttpRequest 對象。
不過,W3C DOM Level 3 的 "Load and Save" 規范包含了一些相似的功能性,但是還沒有任何瀏覽器實現它們。