<!--PHP编程实战-->
<!--JSON & Ajax -->
<!--15-8-->
<!--使用XMLHttpRequest抓取XML文件并解析特殊的值-->
<html>
<head>
<style type="text/css">
#generated_content {
border: 1px solid black;
widht: 300px;
background-color: #dddddd;
padding: 20px;
}
</style>
</head>
<body>
<p><strong>Ajax grabbed specific XML below:</strong></p>
<div id="generated_content"> </div>
<script type="text/javascript">
var xhr = new XMLHttpRequest();
xhr.open("GET", "animals.xml", true);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
var message = "";
if (xhr.status = 200) {
// ----------------------- XML的DOM解析
var xml_data = xhr.responseXML;
var names = xml_data.getElementsByTagName("name");
for (i =0; i < names.length; ++i) {
message += names[i].firstChild.nodeValue + "<br/>\n"; //如 "snoopy\n"
}
// ------------------------
}
else {
message = "An error has occured making the request";
}
document.getElementById("generated_content").innerHTML = message;
}
}
xhr.send(null);
</script>
</body>
</html>
- getElementsByTagName()获取DOM节点集合