AJAX的服務(wù)器響應(yīng)內(nèi)容
ajax的服務(wù)器響應(yīng)內(nèi)容:
使用XMLHttpRequest對象的responseText或者responseXML屬性可以獲取來自服務(wù)器的響應(yīng)內(nèi)容。
兩個屬性功能列表如下:
屬性 | 描述 |
responseText?? | 獲得字符串形式的響應(yīng)數(shù)據(jù)。 |
responseXML | 獲得XML形式的響應(yīng)數(shù)據(jù)。 |
一.responseText屬性:
如果來自服務(wù)器響應(yīng)內(nèi)容不是XML,那么要使用responseText屬性來獲取。此屬性返回值是字符串格式的,使用方式演示如下:
document.getElementById("show").innerHTML=xmlhttp.responseText;
完整代碼實例:
<!DOCTYPE html> <html> <head> <meta charset=" utf-8"> <meta name="author" content="http://www.miracleart.cn/" /> <title>php中文網(wǎng)</title> <script> function loadXMLDoc(){ var xmlhttp; if (window.XMLHttpRequest){ xmlhttp=new XMLHttpRequest(); } else{ xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange=function(){ if(xmlhttp.readyState==4 && xmlhttp.status==200){ document.getElementById("show").innerHTML=xmlhttp.responseText; } } xmlhttp.open("GET","demo/ajax/txt/demo.txt",true); xmlhttp.send(); } window.onload=function(){ var obt=document.getElementById("bt"); obt.onclick=function(){ loadXMLDoc(); } } </script> </head> <body> <div id="show"><h2>原來的內(nèi)容</h2></div> <button type="button" id="bt">查看效果</button> </body> </html>
點擊按鈕可以獲取文本文件中的內(nèi)容,并通過responseText屬性寫入到div中。
二.responseXML屬性:
如果來自服務(wù)器的響應(yīng)是XML,并且需要作為XML對象進行解析,那么就需要使用responseXML屬性,使用方式演示如下:
var xmlDoc = xmlhttp.responseXML;
responseXML屬性的返回值是一個XML對象,完整對象實例如下:
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <meta name="author" content="http://www.miracleart.cn/" /> <title>php中文網(wǎng)</title> <script> function loadXMLDoc() { var xmlhttp; if (window.XMLHttpRequest) { xmlhttp = new XMLHttpRequest(); } else { xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange = function () { if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { var xmlDoc = xmlhttp.responseXML; var str = ""; var targets = xmlDoc.getElementsByTagName("target"); for (index = 0; index < targets.length; index++) { str = str + targets[index].childNodes[0].nodeValue + "<br>"; } document.getElementById("show").innerHTML = str; } } xmlhttp.open("GET", "demo/ajax/xml/XML.xml", true); xmlhttp.send(); } window.onload = function () { var obt = document.getElementById("bt"); obt.onclick = function () { loadXMLDoc(); } } </script> </head> <body> <div> <div id="show"></div> <input id="bt" type="button" value="查看效果"/> </div> </body> </html>