将响应解析成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" οnclick="startRequest('all');"/>
<br/><br/>
<input type="button" value="View All Listed Northern States" οnclick="startRequest('north');"/>
</form>
</body>
</html>