AJAX server response content
ajax server response content:
Use the responseText or responseXML attribute of the XMLHttpRequest object to obtain the response content from the server.
The two attribute function lists are as follows:
Attribute | Description |
responseText | Get the response as a string data. |
responseXML | Get the response data in XML form. |
1.responseText attribute:
If the response content from the server is not XML, then use the responseText attribute to obtain it. The return value of this attribute is in string format. The usage is demonstrated as follows:
document.getElementById("show").innerHTML=xmlhttp.responseText;
Full code example:
<!DOCTYPE html> <html> <head> <meta charset=" utf-8"> <meta name="author" content="http://www.php.cn/" /> <title>php中文网</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>原来的内容</h2></div> <button type="button" id="bt">查看效果</button> </body> </html>
Click the button to get the content in the text file and write it to the text file through the responseText attribute. div.
2.responseXML attribute:
If the response from the server is XML and needs to be parsed as an XML object, then you need to use the responseXML attribute. The usage is demonstrated as follows:
var xmlDoc = xmlhttp.responseXML;
The return value of the responseXML attribute is an XML object. The complete object example is as follows:
<!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.php.cn/" /> <title>php中文网</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>