parsexml.html

例子来源:《Ajax 基础教程》 金灵 等译 这本书非常不错

parsexml.html

<html>
<head>
<title>Parsing XML Responses with the W3C DOm</title>
<script>

var xmlHttp;

var requestType = "";

function createXMLHttpRequest() {
	if (window.ActiveXObject) {
		xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
	}
	else if (window.XMLHttpRequest) {
		xmlHttp = new XMLHttpRequest();
	}
}

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(xmlHttp.status == 200) {
			if(requestType == "north") {
				listNorthStates();
			}
			else if(requestType == "all") {
				listAllStates();
			}
		}
	}
}

function listNorthStates() {
	var xmlDoc = xmlHttp.responseXML;
	var northNode = xmlDoc.getElementsByTagName("north")[0];
	var northStates = northNode.getElementsByTagName("state");
	outputList("Northern states", northStates);
}

function listAllStates() {
	var xmlDoc = xmlHttp.responseXML;
	var allStates = xmlDoc.getElementsByTagName("state");
	outputList("All States in Document", allStates);
}

function outputList(title, states) {
	var out = title;
	var currentState = null;
	for(var i = 0; i < states.length; i++) {
		currentState = states[i];
		out = out + "\n- " + currentState.childNodes[0].nodeValue;
	}
	alert(out);
}
</script>
</head>
<body>
<h1>Process XML Document of U.S.States</h1>
<br /><br />
<form action="#">
	<input type="button" value="View All Listed States" onclick="startRequest('all');" />
	<input type="button" value="View All Listed Northern States" onclick="startRequest('north');" />
</form>
</body>
</html>


parseXML.xml

<?xml version="1.0" encoding="UTF-8"?>
<states>
	<north>
		<state>Minnesota_1</state>
		<state>Iowa_1</state>
		<state>North Dakota_1</state>
	</north>
	<south>
		<state>Texas</state>
		<state>Oklahoma</state>
		<state>Louisiana</state>
	</south>
	<east>
		<state>New York</state>
		<state>North Carolina</state>
		<state>Massachusetts</state>
	</east>
	<west>
		<state>California</state>
		<state>Oregon</state>
		<state>Nevada</state>
	</west>
</states>

你可能感兴趣的:(html,xml,Ajax,Microsoft)