The XMLHttpRequest 對象
通過 XMLHttpRequest 對象,您可以在不重新加載整個頁面的情況下更新網頁中的某個部分。
XMLHttpRequest 對象
XMLHttpRequest 對象用于幕后與服務器交換數(shù)據(jù)。
XMLHttpRequest 對象是開發(fā)者的夢想,因為您可以:
在不重新加載頁面的情況下更新網頁
在頁面已加載后從服務器請求數(shù)據(jù)
在頁面已加載后從服務器接收數(shù)據(jù)
在后臺向服務器發(fā)送數(shù)據(jù)
創(chuàng)建 XMLHttpRequest 對象
所有現(xiàn)代的瀏覽器(IE7+、Firefox、Chrome、Safari 和 Opera)都有一個內建的 XMLHttpRequest 對象。
創(chuàng)建 XMLHttpRequest 對象的語法
舊版本的 Internet Explorer(IE5 和 IE6)使用 ActiveX 對象:
為了處理所有現(xiàn)代的瀏覽器,包括 IE5 和 IE6,請檢查瀏覽器是否支持 XMLHttpRequest 對象。如果支持,則創(chuàng)建一個 XMLHttpRequest 對象,如果不支持,則創(chuàng)建一個 ActiveX 對象:
實例
<!DOCTYPE html> <html> <head> <script> function loadXMLDoc() { if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); } else {// code for IE6, IE5 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { document.getElementById("myDiv").innerHTML=xmlhttp.responseText; } } xmlhttp.open("GET","xmlhttp_info.txt",true); xmlhttp.send(); } </script> </head> <body> <h2>Using the XMLHttpRequest object</h2> <div id="myDiv"></div> <button type="button" onclick="loadXMLDoc()">Change Content</button> </body> </html>
運行實例 ?
點擊 "運行實例" 按鈕查看在線實例
發(fā)送一個請求到服務器
為了發(fā)送一個請求到服務器,我們使用 XMLHttpRequest 對象的 open() 和 send() 方法:
xmlhttp.send();
方法 | 描述 |
---|---|
open(method,url,async) | 規(guī)定請求的類型,URL,請求是否應該進行異步處理。 method:請求的類型:GET 或 POST url:文件在服務器上的位置 async:true(異步)或 false(同步) |
send(string) | 發(fā)送請求到服務器。 string:僅用于 POST 請求 |
GET 或 POST?
GET 比 POST 簡單并且快速,可用于大多數(shù)情況下。
然而,下面的情況下請始終使用 POST 請求:
緩存的文件不是一個選項(更新服務器上的文件或數(shù)據(jù)庫)
發(fā)送到服務器的數(shù)據(jù)量較大(POST 沒有大小的限制)
發(fā)送用戶輸入(可以包含未知字符),POST 比 GET 更強大更安全
URL - 服務器上的文件
open() 方法的 url 參數(shù),是一個在服務器上的文件的地址:
該文件可以是任何類型的文件(如 .txt 和 .xml),或服務器腳本文件(如.html 和 .php,可在發(fā)送回響應之前在服務器上執(zhí)行動作)。
異步 - True 或 False?
如需異步發(fā)送請求,open() 方法的 async 參數(shù)必需設置為 true:
發(fā)送異步請求對于 Web 開發(fā)人員是一個巨大的進步。在服務器上執(zhí)行的許多任務非常費時。
通過異步發(fā)送,JavaScript 不需要等待服務器的響應,但可以替換為:
等待服務器的響應時,執(zhí)行其他腳本
響應準備時處理響應
Async=true
當使用 async=true 時,在 onreadystatechange 事件中響應準備時規(guī)定一個要執(zhí)行的函數(shù):
實例
<!DOCTYPE html> <html> <head> <script> function loadXMLDoc() { if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); } else {// code for IE6, IE5 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { document.getElementById("myDiv").innerHTML=xmlhttp.responseText; } } xmlhttp.open("GET","xmlhttp_info.txt",true); xmlhttp.send(); } </script> </head> <body> <h2>Using the XMLHttpRequest object</h2> <div id="myDiv"></div> <button type="button" onclick="loadXMLDoc()">Change Content</button> </body> </html>
運行實例 ?
點擊 "運行實例" 按鈕查看在線實例
Async=false
如需使用 async=false,請更改 open() 方法的第三個參數(shù)為 false:
不推薦使用 async=false,但如果處理幾個小的請求還是可以的。
請記住,JavaScript 在服務器響應準備之前不會繼續(xù)執(zhí)行。如果服務器正忙或緩慢,應用程序將掛起或停止。
注意:當您使用 async=false 時,不要編寫 onreadystatechange 函數(shù) - 只需要把代碼放置在 send() 語句之后即可:
實例
<!DOCTYPE html> <html> <head> <script> function loadXMLDoc() { xmlhttp=null; if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); } else {// code for IE6, IE5 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } if (xmlhttp!=null) { xmlhttp.open("GET","xmlhttp_info.txt",false); xmlhttp.send(); document.getElementById("myDiv").innerHTML=xmlhttp.responseText; } else { alert("Your browser does not support XMLHTTP."); } } </script> </head> <body> <h2>Using the XMLHttpRequest object</h2> <div id="myDiv"></div> <button type="button" onclick="loadXMLDoc()">Change Content</button> </body> </html>
運行實例 ?
點擊 "運行實例" 按鈕查看在線實例
服務器響應
如需從服務器獲取響應,請使用 XMLHttpRequest 對象的 responseText 或 responseXML 屬性。
屬性 | 描述 |
---|---|
responseText | 獲取響應數(shù)據(jù)作為字符串 |
responseXML | 獲取響應數(shù)據(jù)作為 XML 數(shù)據(jù) |
responseText 屬性
如果來自服務器的響應不是 XML,請使用 responseText 屬性。
responseText 屬性以字符串形式返回響應,您可以相應地使用它:
實例
<!DOCTYPE html> <html> <head> <script> function loadXMLDoc() { if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); } else {// code for IE6, IE5 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { document.getElementById("myDiv").innerHTML=xmlhttp.responseText; } } xmlhttp.open("GET","xmlhttp_info.txt",true); xmlhttp.send(); } </script> </head> <body> <h2>Using the XMLHttpRequest object</h2> <div id="myDiv"></div> <button type="button" onclick="loadXMLDoc()">Change Content</button> </body> </html>
運行實例 ?
點擊 "運行實例" 按鈕查看在線實例
responseXML 屬性
如果來自服務器的響應不是 XML,且您想要把它解析為 XML 對象,請使用 responseXML 屬性:
實例
請求文件 cd_catalog.xml 并解析響應:
<!DOCTYPE html> <html> <head> <script> function loadXMLDoc() { xmlhttp=null; if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); } else {// code for IE6, IE5 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } if (xmlhttp!=null) { xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { xmlDoc=xmlhttp.responseXML; var txt=""; x=xmlDoc.getElementsByTagName("ARTIST"); for (i=0;i<x.length;i++) { txt=txt + x[i].childNodes[0].nodeValue + "<br>"; } document.getElementById("myDiv").innerHTML=txt; } } xmlhttp.open("GET","cd_catalog.xml",true); xmlhttp.send(); } else { alert("Your browser does not support XMLHTTP."); } } </script> </head> <body> <h2>My CD Collection:</h2> <div id="myDiv"></div> <button type="button" onclick="loadXMLDoc()">Get my CD collection</button> </body> </html>
運行實例 ?
點擊 "運行實例" 按鈕查看在線實例
onreadystatechange 事件
當請求被發(fā)送到服務器,我們要根據(jù)響應執(zhí)行某些動作。
onreadystatechange 事件在每次 readyState 變化時被觸發(fā)。
readyState 屬性持有 XMLHttpRequest 的狀態(tài)。
XMLHttpRequest 對象的三個重要的屬性:
屬性 | 描述 |
---|---|
onreadystatechange | 存儲函數(shù)(或函數(shù)的名稱)在每次 readyState 屬性變化時被自動調用 |
readyState | 存放了 XMLHttpRequest 的狀態(tài)。從 0 到 4 變化: 0:請求未初始化 1:服務器建立連接 2:收到的請求 3:處理請求 4:請求完成和響應準備就緒 |
status | 200:"OK" 404:找不到頁面 |
在 onreadystatechange 事件中,我們規(guī)定當服務器的響應準備處理時會發(fā)生什么。
當 readyState 是 4 或狀態(tài)是 200 時,響應準備:
實例
<!DOCTYPE html> <html> <head> <script> function loadXMLDoc() { if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); } else {// code for IE6, IE5 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { document.getElementById("myDiv").innerHTML=xmlhttp.responseText; } } xmlhttp.open("GET","xmlhttp_info.txt",true); xmlhttp.send(); } </script> </head> <body> <h2>Using the XMLHttpRequest object</h2> <div id="myDiv"></div> <button type="button" onclick="loadXMLDoc()">Change Content</button> </body> </html>
運行實例 ?
點擊 "運行實例" 按鈕查看在線實例
注意:onreadystatechange 事件在每次 readyState 發(fā)生變化時被觸發(fā),總共觸發(fā)了四次。
更多實例
通過 getAllResponseHeaders() 檢索頭信息
檢索資源(文件)的頭信息。
實例
<!DOCTYPE html> <html> <head> <script> function loadXMLDoc(url) { if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); } else {// code for IE6, IE5 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { document.getElementById('p1').innerHTML=xmlhttp.getAllResponseHeaders(); } } xmlhttp.open("GET",url,true); xmlhttp.send(); } </script> </head> <body> <p id="p1">The getAllResponseHeaders() function returns the header information of a resource, like length, server-type, content-type, last-modified, etc.</p> <button onclick="loadXMLDoc('xmlhttp_info.txt')">Get header information</button> </body> </html>
運行實例 ?
點擊 "運行實例" 按鈕查看在線實例
通過 getResponseHeader() 檢索指定頭信息
檢索資源(文件)的指定頭信息。
實例
<!DOCTYPE html> <html> <head> <script> function loadXMLDoc(url) { if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); } else {// code for IE6, IE5 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { document.getElementById('p1').innerHTML="Last modified: " + xmlhttp.getResponseHeader('Last-Modified'); } } xmlhttp.open("GET",url,true); xmlhttp.send(); } </script> </head> <body> <p id="p1">The getResponseHeader() function is used to return specific header information from a resource, like length, server-type, content-type, last-modified, etc.</p> <button onclick="loadXMLDoc('xmlhttp_info.txt')">Get "Last-Modified" information</button> </body> </html>
運行實例 ?
點擊 "運行實例" 按鈕查看在線實例
檢索 ASP 文件的內容
當用戶在輸入字段鍵入字符時,網頁如何與 Web 服務器進行通信。
實例
<!DOCTYPE html> <html> <head> <script> function showHint(str) { if (str.length==0) { document.getElementById("txtHint").innerHTML=""; return; } if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); } else {// code for IE6, IE5 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { document.getElementById("txtHint").innerHTML=xmlhttp.responseText; } } xmlhttp.open("GET","gethint.php?q="+str,true); xmlhttp.send(); } </script> </head> <body> <h3>Start typing a name in the input field below:</h3> <form action=""> First name: <input type="text" id="txt1" onkeyup="showHint(this.value)" /> </form> <p>Suggestions: <span id="txtHint"></span></p> </body> </html>
運行實例 ?
點擊 "運行實例" 按鈕查看在線實例
從數(shù)據(jù)庫中檢索內容
網頁如何通過 XMLHttpRequest 對象從數(shù)據(jù)庫中提取信息。
實例
<!DOCTYPE html> <html> <head> <script> function showCustomer(str) { if (str=="") { document.getElementById("txtHint").innerHTML=""; return; } if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); } else {// code for IE6, IE5 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { document.getElementById("txtHint").innerHTML=xmlhttp.responseText; } } xmlhttp.open("GET","getcustomer.php?q="+str,true); xmlhttp.send(); } </script> </head> <body> <form action=""> <select name="customers" onchange="showCustomer(this.value)"> <option value="">Select a customer:</option> <option value="ALFKI">Alfreds Futterkiste</option> <option value="NORTS ">North/South</option> <option value="WOLZA">Wolski Zajazd</option> </select> </form> <br> <div id="txtHint">Customer info will be listed here...</div> </body> </html>
運行實例 ?
點擊 "運行實例" 按鈕查看在線實例
檢索 XML 文件的內容
創(chuàng)建一個 XMLHttpRequest 從 XML 文件中檢索數(shù)據(jù)并把數(shù)據(jù)顯示在一個 HTML 表格中。
實例
<!DOCTYPE html> <html> <head> <script> function loadXMLDoc(url) { if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); } else {// code for IE6, IE5 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { txt="<table border='1'><tr><th>Title</th><th>Artist</th></tr>"; x=xmlhttp.responseXML.documentElement.getElementsByTagName("CD"); for (i=0;i<x.length;i++) { txt=txt + "<tr>"; xx=x[i].getElementsByTagName("TITLE"); { try { txt=txt + "<td>" + xx[0].firstChild.nodeValue + "</td>"; } catch (er) { txt=txt + "<td> </td>"; } } xx=x[i].getElementsByTagName("ARTIST"); { try { txt=txt + "<td>" + xx[0].firstChild.nodeValue + "</td>"; } catch (er) { txt=txt + "<td> </td>"; } } txt=txt + "</tr>"; } txt=txt + "</table>"; document.getElementById('txtCDInfo').innerHTML=txt; } } xmlhttp.open("GET",url,true); xmlhttp.send(); } </script> </head> <body> <div id="txtCDInfo"> <button onclick="loadXMLDoc('cd_catalog.xml')">Get CD info</button> </div> </body> </html>
運行實例 ?
點擊 "運行實例" 按鈕查看在線實例