这个是parseXML.html的代码:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<title>Parsing XML Response with W3C DOM</title>
</head>
<script language="javascript">
var xmlHttp;
var requestType = "";
function createXMLHttpRequest() {
if(window.ActiveXObject) {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
else if(window.XMLHttpRequest) {
xmlHttp = new XMLHttpRequest();
}
else {
return;
}
}
function startRequest(requestedList) {
requestType = requestedList;
createXMLHttpRequest();
xmlHttp.onreadystatechange = handleStateChange;
xmlHttp.open("GET", "parseXML.xml", true);
xmlHttp.send(null);
}
function handleStateChange() {
if(xmlHttp.readyState == 4) {
if(requestType == "north") {
listNorthStates();
}
else if(requestType == "all") {
listAllStates();
}
}
}
function listNorthStates() {
var xmlDoc = xmlHttp.responseXML;
var northNode = xmlDoc.getElementsByTagName("north")[0];
alert(northNode);
var out = "Northern States";
alert(northNode.getElementsByTagName("state"));
var northStates = northNode.getElementsByTagName("state");
outputList(out, northStates);
}
function listAllStates() {
var xmlDoc = xmlHttp.responseXML;
var out = "All States";
var allStates = xmlDoc.getElementsByTagName("state")
outputList(out, allStates)
}
function outputList(title, states) {
var currentState = null;
for(var i=0; i<states.length; i++) {
currentState = state[i];
var out = title + "\n-" + currentState.childNodes[0].nodeValue;
}
alert(out);
}
</script>
<body>
<input name="test" type="button" value="View All Listed States" onClick="startRequest('all');">
</body>
</html>
这个是parseXML.xml的代码:
<?xml version="1.0" encoding="UTF-8"?>
<states>
<north>
<state>a</state>
<state>b</state>
<state>c</state>
</north>
<west>
<state>d</state>
<state>e</state>
<state>f</state>
</west>
</states>