index.html:
<!DOCTYPE html>
<html>
<head>
<Meta charset="UTF-8">
<title></title>
<style type="text/css"> ul { font-size: 14pt; } </style>
<script type="text/javascript"> function loadData(txt) { var request = new XMLHttpRequest(); var method = "GET"; var url = txt + ".xml"; request.open(method,url); request.send(null); request.onreadystatechange = function() { if(request.readyState == 4) { if(request.status == 200) { //返回的是xml 一个document对象,那么就可以利用dom的方法来操作 var xmlDoc = request.responseXML; /* * 返回的数据 : * <?xml version="1.0" encoding="UTF-8"?> * <root> * <name>AAA</name> * <email>AAAA@gmail.com</email> * </root> * */ /* * 要创建的: <h2>AAA</h2> * <p>email:AAA@gmail.com</p> */ var name = xmlDoc.getElementsByTagName("name")[0].firstChild.nodeValue; var email = xmlDoc.getElementsByTagName("email")[0].firstChild.nodeValue; var h2Node = document.createElement("h2"); h2Node.appendChild(document.createTextNode(name)); var pNode = document.createElement("p"); pNode.appendChild(document.createTextNode(email)); var detail = document.getElementById("detail"); //清空div原来的内容 detail.innerHTML = ""; detail.appendChild(h2Node); detail.appendChild(pNode); } } } } </script>
</head>
<body>
<p>点击对应会显示详细信息,ajax请求服务器上的数据,将详细信息显示在下方</p>
<ul>
<li>
<a onclick="loadData('AAA')">AAA</a>
</li>
<li>
<a onclick="loadData('BBB')">BBB</a>
</li>
<li>
<a onclick="loadData('CCC')">CCC</a>
</li>
</ul>
<div id="detail"></div>
</body>
</html>
AAA.xml:
<?xml version="1.0" encoding="UTF-8"?>
<root>
<name>AAA</name>
<email>AAAA@gmail.com</email>
</root>
BBB.html:
<?xml version="1.0" encoding="UTF-8"?>
<root>
<name>BBB</name>
<email>BBB@gmail.com</email>
</root>
CCC.html:
<?xml version="1.0" encoding="UTF-8"?>
<root>
<name>CCC</name>
<email>CCCC@gmail.com</email>
</root>