Ajax返回xml类型数据
ajax可以返回文本类型数据和xml类型数据,xml是计算机通用语言 可以使用js解析返回xml类型数据的dom对象
前端页面
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="Generator" content="EditPlus®"> <meta name="Author" content=""> <meta name="Keywords" content=""> <meta name="Description" content=""> <title>Ajax</title> <script type="text/javascript"> function createXHR(){ var xhr=null; if(window.XMLHttpRequest){ xhr=new XMLHttpRequest(); }else if(window.ActiveXObject){ xhr=new ActiveXObject('Microsoft.XMLHttp'); } return xhr; } function returnxml(){ var xhr=createXHR(); xhr.open('GET','./returnxml.php',true); xhr.onreadystatechange=function (){ if(this.readyState==4&&this.status==200){ //alert(this.responseXML);//[object XMLDocument] var xmldom=this.responseXML; var title=xmldom.getElementsByTagName('title')[0]; var title=title.firstChild.wholeText; var str='书名:'+title+'<br/>'; var price=xmldom.getElementsByTagName('price')[0].firstChild.wholeText; var desc=xmldom.getElementsByTagName('desc')[0].firstChild.wholeText; str=str+'价格:'+price+'<br/>'; str=str+'详细信息:'+desc+'<br/>'; str=str+'状态码:'+this.status+'<br/>'; str=str+'状态文字:'+this.statusText+'<br/>'; str=str+'返回值类型:'+this.getResponseHeader('content-type')+'<br/>'; str=str+'返回值长度:'+this.getResponseHeader('content-length')+'<br/>'; str=str+'ip:'+this.getResponseHeader('x-forwarded-for')+'<br/>'; document.getElementById('book').innerHTML=str; } } xhr.send(null); } </script> </head> <body> <input type="button" value="返回值xml" onclick="returnxml();"/> <div id="book"></div> </body> </html>
returnxml.php
<?php header('content-type:text/xml'); ?> <?xml version="1.0" encoding="utf8" ?> <bookstore><book><title>ajax详解</title><price>39.9元</price><desc>学习ajax的最强帮</desc></book></bookstore>
结果显示效果