XMLHttpRequest 提供了兩個用來存取伺服器回應的屬性:responseText 把回應當成字串,responseXML 則把它當成 XML 物件。
有些場景用純文字就夠了——把回應丟進警告框、或回應只是一個代表成功或失敗的詞。但先前〈Ajax 小結〉裡用的是 responseText;這次換成 responseXML,如此一來就能用 W3C DOM 的方法去遍歷整份 XML 文件。
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>
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://" + request.getServerName()
+ ":" + request.getServerPort() + path + "/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'MyJsp.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
</head>>
<script type="text/javascript">
var flg = false;
var requestType = "";
// 取得 XMLHttpRequest 物件
function newXMLHttpRequest() {
var xmlreq = false;
if (window.XMLHttpRequest) {
xmlreq = new XMLHttpRequest();
} else if (window.ActiveXObject) {
try {
xmlreq = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e1) {
try {
xmlreq = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e2) {}
}
}
return xmlreq;
}
function startRequest(requestedList){
requestType = requestedList;
flg = newXMLHttpRequest();
// readyState 改變時回呼 handleStateChange
flg.onreadystatechange = handleStateChange;
flg.open("GET", "parseXML.xml", true);
flg.send(null);
}
function handleStateChange(){
if (flg.readyState == 4) {
if (flg.status == 200) {
if (requestType == "north") { listNorthStates(); }
else if (requestType == "all") { listAllStates(); }
else if (requestType == "south") { listSouthStates(); }
}
}
}
// 只取 north 底下的 state
function listNorthStates(){
var xmlDoc = flg.responseXML;
var northNode = xmlDoc.getElementsByTagName("north")[0];
var northStates = northNode.getElementsByTagName("state");
outputList("North States", northStates);
}
function listSouthStates(){
var xmlDoc = flg.responseXML;
var southNode = xmlDoc.getElementsByTagName("south")[0];
var southStates = southNode.getElementsByTagName("state");
outputList("South States", southStates);
}
// 取整份文件中的所有 state
function listAllStates(){
var xmlDoc = flg.responseXML;
var allStates = xmlDoc.getElementsByTagName("state");
outputList("All States in Document", allStates);
}
// 輸出並以提示框顯示
function outputList(title, states){
var out = title;
for (var i = 0; i < states.length; i++) {
out = out + "\n - " + states[i].childNodes[0].nodeValue;
}
alert(out);
}
</script>
<body>
<form action="#">
<input type="button" value="View All Listed States"
onclick="startRequest('all');" /><br>
<input type="button" value="View All Listed Northern States"
onclick="startRequest('north');" /><br>
<input type="button" value="View All Listed Southern States"
onclick="startRequest('south');" />
</form>
</body>
</html>
getElementsByTagName 是階層相關的。 xmlDoc.getElementsByTagName("north")[0] 先定位到 north 節點,再對它呼叫一次同名方法,取到的就只是 north 底下的 state——這正是範例中「只看北部」與「看全部」能有不同結果的原因。
讀文字內容要鑽到 text node。 states[i].childNodes[0].nodeValue 才是標籤之間真正的文字;直接對元素節點取值會得到 null。
responseXML 有前提。 伺服器回傳的 Content-Type 必須是 text/xml 或 application/xml,否則 responseXML 會是 null。靜態 .xml 檔通常沒問題,但若是動態產生的輸出,這一步很容易漏設。
最後一點現實考量:responseXML 這套 DOM 操作如今已顯得笨重。新專案建議直接抓 JSON,用 JSON.parse 或 jQuery 的 dataType: "json" 處理,程式碼量能少一半以上。只有在需要對接既有 XML 服務(如 SOAP、舊版 RSS)時,才值得走這條路。