The XMLHttpRequest 對(duì)象
通過(guò) XMLHttpRequest 對(duì)象,您可以在不重新加載整個(gè)頁(yè)面的情況下更新網(wǎng)頁(yè)中的某個(gè)部分。
XMLHttpRequest 對(duì)象
XMLHttpRequest 對(duì)象用于幕后與服務(wù)器交換數(shù)據(jù)。
XMLHttpRequest 對(duì)象是開(kāi)發(fā)者的夢(mèng)想,因?yàn)槟梢裕?/p>
在不重新加載頁(yè)面的情況下更新網(wǎng)頁(yè)
在頁(yè)面已加載后從服務(wù)器請(qǐng)求數(shù)據(jù)
在頁(yè)面已加載后從服務(wù)器接收數(shù)據(jù)
在后臺(tái)向服務(wù)器發(fā)送數(shù)據(jù)
創(chuàng)建 XMLHttpRequest 對(duì)象
所有現(xiàn)代的瀏覽器(IE7+、Firefox、Chrome、Safari 和 Opera)都有一個(gè)內(nèi)建的 XMLHttpRequest 對(duì)象。
創(chuàng)建 XMLHttpRequest 對(duì)象的語(yǔ)法
舊版本的 Internet Explorer(IE5 和 IE6)使用 ActiveX 對(duì)象:
為了處理所有現(xiàn)代的瀏覽器,包括 IE5 和 IE6,請(qǐng)檢查瀏覽器是否支持 XMLHttpRequest 對(duì)象。如果支持,則創(chuàng)建一個(gè) XMLHttpRequest 對(duì)象,如果不支持,則創(chuàng)建一個(gè) ActiveX 對(duì)象:
實(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>
運(yùn)行實(shí)例 ?
點(diǎn)擊 "運(yùn)行實(shí)例" 按鈕查看在線(xiàn)實(shí)例
發(fā)送一個(gè)請(qǐng)求到服務(wù)器
為了發(fā)送一個(gè)請(qǐng)求到服務(wù)器,我們使用 XMLHttpRequest 對(duì)象的 open() 和 send() 方法:
xmlhttp.send();
方法 | 描述 |
---|---|
open(method,url,async) | 規(guī)定請(qǐng)求的類(lèi)型,URL,請(qǐng)求是否應(yīng)該進(jìn)行異步處理。 method:請(qǐng)求的類(lèi)型:GET 或 POST url:文件在服務(wù)器上的位置 async:true(異步)或 false(同步) |
send(string) | 發(fā)送請(qǐng)求到服務(wù)器。 string:僅用于 POST 請(qǐng)求 |
GET 或 POST?
GET 比 POST 簡(jiǎn)單并且快速,可用于大多數(shù)情況下。
然而,下面的情況下請(qǐng)始終使用 POST 請(qǐng)求:
緩存的文件不是一個(gè)選項(xiàng)(更新服務(wù)器上的文件或數(shù)據(jù)庫(kù))
發(fā)送到服務(wù)器的數(shù)據(jù)量較大(POST 沒(méi)有大小的限制)
發(fā)送用戶(hù)輸入(可以包含未知字符),POST 比 GET 更強(qiáng)大更安全
URL - 服務(wù)器上的文件
open() 方法的 url 參數(shù),是一個(gè)在服務(wù)器上的文件的地址:
該文件可以是任何類(lèi)型的文件(如 .txt 和 .xml),或服務(wù)器腳本文件(如.html 和 .php,可在發(fā)送回響應(yīng)之前在服務(wù)器上執(zhí)行動(dòng)作)。
異步 - True 或 False?
如需異步發(fā)送請(qǐng)求,open() 方法的 async 參數(shù)必需設(shè)置為 true:
發(fā)送異步請(qǐng)求對(duì)于 Web 開(kāi)發(fā)人員是一個(gè)巨大的進(jìn)步。在服務(wù)器上執(zhí)行的許多任務(wù)非常費(fèi)時(shí)。
通過(guò)異步發(fā)送,JavaScript 不需要等待服務(wù)器的響應(yīng),但可以替換為:
等待服務(wù)器的響應(yīng)時(shí),執(zhí)行其他腳本
響應(yīng)準(zhǔn)備時(shí)處理響應(yīng)
Async=true
當(dāng)使用 async=true 時(shí),在 onreadystatechange 事件中響應(yīng)準(zhǔn)備時(shí)規(guī)定一個(gè)要執(zhí)行的函數(shù):
實(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>
運(yùn)行實(shí)例 ?
點(diǎn)擊 "運(yùn)行實(shí)例" 按鈕查看在線(xiàn)實(shí)例
Async=false
如需使用 async=false,請(qǐng)更改 open() 方法的第三個(gè)參數(shù)為 false:
不推薦使用 async=false,但如果處理幾個(gè)小的請(qǐng)求還是可以的。
請(qǐng)記住,JavaScript 在服務(wù)器響應(yīng)準(zhǔn)備之前不會(huì)繼續(xù)執(zhí)行。如果服務(wù)器正忙或緩慢,應(yīng)用程序?qū)炱鸹蛲V埂?/p>
注意:當(dāng)您使用 async=false 時(shí),不要編寫(xiě) onreadystatechange 函數(shù) - 只需要把代碼放置在 send() 語(yǔ)句之后即可:
實(shí)例
<!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>
運(yùn)行實(shí)例 ?
點(diǎn)擊 "運(yùn)行實(shí)例" 按鈕查看在線(xiàn)實(shí)例
服務(wù)器響應(yīng)
如需從服務(wù)器獲取響應(yīng),請(qǐng)使用 XMLHttpRequest 對(duì)象的 responseText 或 responseXML 屬性。
屬性 | 描述 |
---|---|
responseText | 獲取響應(yīng)數(shù)據(jù)作為字符串 |
responseXML | 獲取響應(yīng)數(shù)據(jù)作為 XML 數(shù)據(jù) |
responseText 屬性
如果來(lái)自服務(wù)器的響應(yīng)不是 XML,請(qǐng)使用 responseText 屬性。
responseText 屬性以字符串形式返回響應(yīng),您可以相應(yīng)地使用它:
實(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>
運(yùn)行實(shí)例 ?
點(diǎn)擊 "運(yùn)行實(shí)例" 按鈕查看在線(xiàn)實(shí)例
responseXML 屬性
如果來(lái)自服務(wù)器的響應(yīng)不是 XML,且您想要把它解析為 XML 對(duì)象,請(qǐng)使用 responseXML 屬性:
實(shí)例
請(qǐng)求文件 cd_catalog.xml 并解析響應(yīng):
<!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>
運(yùn)行實(shí)例 ?
點(diǎn)擊 "運(yùn)行實(shí)例" 按鈕查看在線(xiàn)實(shí)例
onreadystatechange 事件
當(dāng)請(qǐng)求被發(fā)送到服務(wù)器,我們要根據(jù)響應(yīng)執(zhí)行某些動(dòng)作。
onreadystatechange 事件在每次 readyState 變化時(shí)被觸發(fā)。
readyState 屬性持有 XMLHttpRequest 的狀態(tài)。
XMLHttpRequest 對(duì)象的三個(gè)重要的屬性:
屬性 | 描述 |
---|---|
onreadystatechange | 存儲(chǔ)函數(shù)(或函數(shù)的名稱(chēng))在每次 readyState 屬性變化時(shí)被自動(dòng)調(diào)用 |
readyState | 存放了 XMLHttpRequest 的狀態(tài)。從 0 到 4 變化: 0:請(qǐng)求未初始化 1:服務(wù)器建立連接 2:收到的請(qǐng)求 3:處理請(qǐng)求 4:請(qǐng)求完成和響應(yīng)準(zhǔn)備就緒 |
status | 200:"OK" 404:找不到頁(yè)面 |
在 onreadystatechange 事件中,我們規(guī)定當(dāng)服務(wù)器的響應(yīng)準(zhǔn)備處理時(shí)會(huì)發(fā)生什么。
當(dāng) readyState 是 4 或狀態(tài)是 200 時(shí),響應(yīng)準(zhǔn)備:
實(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>
運(yùn)行實(shí)例 ?
點(diǎn)擊 "運(yùn)行實(shí)例" 按鈕查看在線(xiàn)實(shí)例
注意:onreadystatechange 事件在每次 readyState 發(fā)生變化時(shí)被觸發(fā),總共觸發(fā)了四次。
更多實(shí)例
通過(guò) getAllResponseHeaders() 檢索頭信息
檢索資源(文件)的頭信息。
實(shí)例
<!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>
運(yùn)行實(shí)例 ?
點(diǎn)擊 "運(yùn)行實(shí)例" 按鈕查看在線(xiàn)實(shí)例
通過(guò) getResponseHeader() 檢索指定頭信息
檢索資源(文件)的指定頭信息。
實(shí)例
<!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>
運(yùn)行實(shí)例 ?
點(diǎn)擊 "運(yùn)行實(shí)例" 按鈕查看在線(xiàn)實(shí)例
檢索 ASP 文件的內(nèi)容
當(dāng)用戶(hù)在輸入字段鍵入字符時(shí),網(wǎng)頁(yè)如何與 Web 服務(wù)器進(jìn)行通信。
實(shí)例
<!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>
運(yùn)行實(shí)例 ?
點(diǎn)擊 "運(yùn)行實(shí)例" 按鈕查看在線(xiàn)實(shí)例
從數(shù)據(jù)庫(kù)中檢索內(nèi)容
網(wǎng)頁(yè)如何通過(guò) XMLHttpRequest 對(duì)象從數(shù)據(jù)庫(kù)中提取信息。
實(shí)例
<!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>
運(yùn)行實(shí)例 ?
點(diǎn)擊 "運(yùn)行實(shí)例" 按鈕查看在線(xiàn)實(shí)例
檢索 XML 文件的內(nèi)容
創(chuàng)建一個(gè) XMLHttpRequest 從 XML 文件中檢索數(shù)據(jù)并把數(shù)據(jù)顯示在一個(gè) HTML 表格中。
實(shí)例
<!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>
運(yùn)行實(shí)例 ?
點(diǎn)擊 "運(yùn)行實(shí)例" 按鈕查看在線(xiàn)實(shí)例