1、在Eclipse中创建项目目录视图如下:
2、代码及注解如下
<?xml version="1.0" encoding="utf-8" ?> <details> <name>Hello,I am Alice.</name> <website>http://adactio.com</website> <email>Alice@qq.com</email> </details>
<!DOCTYPE html> <html> <head> <Meta charset="UTF-8"> <title>AJAX--XML数据格式</title> <script type="text/javascript"> window.onload = function() { var aNodes = document.getElementsByTagName('a'); for (var i = 0; i < aNodes.length; i++) { aNodes[i].onclick = function() { var request = new XMLHttpRequest(); var method = 'GET'; var url = this.href; request.open(method,url); request.send(null); request.onreadystatechange = function() { if (request.readyState == 4) { if (request.status == 200 || request.status == 304) { // 1、结果为XML格式,所以需要使用responseXML来获取 var result = request.responseXML; // 2、结果不能直接使用,必须先创建对应的节点,再把节点加入到#details中 // 目标格式为: /* <h2><a href="mailto:Alice@qq.com">Hello,I am Alice.</a></h2> <a href="http://andybudd.com">http://andybudd.com</a> */ var name = result.getElementsByTagName('name')[0].firstChild.nodeValue; var website = result.getElementsByTagName('website')[0].firstChild.nodeValue; var email = result.getElementsByTagName('email')[0].firstChild.nodeValue; /* alert(name); alert(website); alert(email); */ // 3.1、创建<a>标签 var aNode = document.createElement('a'); aNode.appendChild(document.createTextNode(name)); aNode.href = 'mailto:' + email; // 3.2、创建h2标签 var h2Node = document.createElement('h2'); h2Node.appendChild(aNode); // 3.3、创建第2个<a>标签 var aNode2 = document.createElement('a'); aNode2.appendChild(document.createTextNode(website)); aNode2.href = website; // 4、将拼写得到的xml数据信息添加到"id = 'detail'"中 var detailsNode = document.getElementById('details'); detailsNode.innerHTML = ""; detailsNode.appendChild(h2Node); detailsNode.appendChild(aNode2); } } // if (request.readyState == 4) } // request.onreadystatechange = function() return false; } // aNodes[i].onclick = function() } // for (var i = 0; i < aNodes.length; i++) } // window.onload = function() </script> </head> <body> <h2>Person</h2> <ul> <li><a href="files/andy.xml">Andy</a></li> <li><a href="files/jeremy.xml">Jeremy</a></li> <li><a href="files/richard.xml">Richard</a></li> </ul> <div id="details"></div> </body> </html>
3、运行结果如下所示: