AJAX與XML文件交互
ajax與XML文件交互:
通過ajax可以與XML文件進行相互交互。
最為典型的應(yīng)用就是讀取XML文件的內(nèi)容,下面就通過代碼實例做一下介紹。
代碼如下:
<!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>
在上面的代碼中,xmlhttp.responseXML返回的是一個xml對象,然后再利用相應(yīng)的dom操作即可實現(xiàn)想要的效果。
xml文件代碼如下:
<?xml version="1.0" encoding="utf-8" ?> <bookstore> <book> <range>前端專區(qū)</range> <author>php中文網(wǎng)</author> <target>css教程</target> </book> <book> <range>前端專區(qū)</range> <author>php中文網(wǎng)</author> <target>div教程</target> </book> <book> <range>資源專區(qū)</range> <author>php.cn</author> <target>特效下載</target> </book> <book> <range>前端專區(qū)</range> <author>php.cn</author> <target>教程下載</target> </book> </bookstore>