將響應解析成XML:
伺服器不一定按XML格式發送響應。只要Content-Type的響應首部設定為text/pain(如果是XML,Content-Type的首部為text/xml)。
XML序言: 定義XML的版本和文檔所用字型的編碼
<?xml version="1.0" encoding="UTF-8"?>
說明:GB2312 (簡體中文),UTF-8是世界通用的語言編碼,.UTF8 是(UNICODE八位交換格式)的簡稱,UNICODE是國際標準,也是ISO標準10646的等價標準。中國大陸簡體中文版非常常用的GB2312/GB18030/GBK系列標準是我國的國家標準,但只能對中文和多數西方文字進行編碼。為了網站的通用性起見,用UTF8編碼是更好的選擇。
xmlHttp.status ==0:
xmlHttp.status=4表示通過伺服器運行,等於0代表在本機上就可以運行,即使沒有通過伺服器(例如tomcat)
例:parseXML.xml:
<?xml version="1.0" encoding="UTF-8"?>
<states>
<north>
<state>Minnesota</state>
<state>Iowa</state>
<state>North Dakota</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>
parseXML.html:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" contect="text/xml";charset=UTF-8">
<title>Parsing XML Responses with the W3C DOM</title>
<script type="text/javascript">
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||xmlHttp.status ==0) {
if(requestType == "north") {
listNorthStates();
}
else if(requestType == "all") {
listAllStates();
}
}
}
}
function listNorthStates() {
var xmlDoc = xmlHttp.responseXML;
var northNode = xmlDoc.getElementsByTagName("north")[0];
var out = "Northern States";
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');"/>
<br/><br/>
<input type="button" value="View All Listed Northern States" onclick="startRequest('north');"/>
</form>
</body>
</html>