用ajax读取xml格式的数据,只需要读取xmlhttprequest对象返回的responsexml属性即可。
用ajax读取xml格式的数据,只需要读取xmlhttprequest对象返回的responsexml属性即可。代码如下:
1、client - helloworld.htm
| 以下是引用片段: <!doctype html public "-//w3c//dtd xhtml 1.0 strict//en" "http://www.w3.org/tr/xhtml1/dtd/xhtml1-strict.dtd"> <html> <head> <title>ajax hello world</title> <script type="text/javascript"> var xmlhttp; function createxmlhttprequest(){ if(window.activexobject){ xmlhttp = new activexobject("microsoft.xmlhttp"); } else if(window.xmlhttprequest){ xmlhttp = new xmlhttprequest(); } } function startrequest(){ createxmlhttprequest(); try{ xmlhttp.onreadystatechange = handlestatechange; xmlhttp.open("get", "data.xml", true); xmlhttp.send(null); }catch(exception){ alert("您要访问的资源不存在!"); } } function handlestatechange(){ if(xmlhttp.readystate == 4){ if (xmlhttp.status == 200 || xmlhttp.status == 0){ // 取得xml的dom对象 var xmldom = xmlhttp.responsexml; // 取得xml文档的根 var root = xmldom.documentelement; try { // 取得<info>结果 var info = root.getelementsbytagname('info'); // 显示返回结果 alert("responsexml's value: " + info[0].firstchild.data); }catch(exception) { } } } } </script> </head> <body> <div> <input type="button" value="return ajax responsexml's value" onclick="startrequest();" /> </div> </body> </html> |
2、server - data.xml
<?xml version="1.0" encoding="gb2312" ?>
<root>
<info>hello world!</info>
</root>
闽公网安备 35060202000074号