服務(wù)器響應(yīng)
如需獲得來自服務(wù)器的響應(yīng),請使用 XMLHttpRequest 對象的 responseText 或 responseXML 屬性。
屬性 | 描述 |
---|---|
responseText | 獲得字符串形式的響應(yīng)數(shù)據(jù)。 |
responseXML | 獲得 XML 形式的響應(yīng)數(shù)據(jù)。 |
responseText 屬性
如果來自服務(wù)器的響應(yīng)并非 XML,請使用 responseText 屬性。
responseText 屬性返回字符串形式的響應(yīng),因此您可以這樣使用:
實例
<html><!DOCTYPE html> <html> <head> <script> function loadXMLDoc() { var xmlhttp; 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","/try/ajax/ajax_info.txt",true); xmlhttp.send(); } </script> </head> <body> <div id="myDiv"><h2>使用 AJAX 修改該文本內(nèi)容</h2></div> <button type="button" onclick="loadXMLDoc()">修改內(nèi)容</button> </body> </html>
運行實例 ?
點擊 "運行實例" 按鈕查看在線實例
responseXML 屬性
如果來自服務(wù)器的響應(yīng)是 XML,而且需要作為 XML 對象進行解析,請使用 responseXML 屬性:
實例
請求 cd_catalog.xml 文件,并解析響應(yīng):
<html><!DOCTYPE html> <html> <head> <script> function loadXMLDoc() { var xmlhttp; var txt,x,i; 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) { xmlDoc=xmlhttp.responseXML; 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(); } </script> </head> <body> <h2>My CD Collection:</h2> <div id="myDiv"></div> <button type="button" onclick="loadXMLDoc()">Get my CD collection</button> </body> </html>
運行實例 ?
點擊 "運行實例" 按鈕查看在線實例