Ajax客户端与伺服端之间,可以使用XML作为数据传送、沟通的格式,Ajax客户端若要发送XML,基本上就是将XML作为字符串,塞在POST本体中发送,例如:
• HandleXMLEx-1.js
var xmlHttp;
function createXMLHttpRequest() {
if(window.XMLHttpRequest) {
xmlHttp = new XMLHttpRequest();
}
else if(window.ActiveXObject) {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
}
function prepareXML() {
var xml = "<skills>";
var options = document.getElementById("skills").childNodes;
for(var i = 0; i < options.length; i++) {
var option = options[i];
if(option.selected) {
xml = xml + "<skill>" + option.value + "<\/skill>";
}
}
xml = xml + "<\/skills>";
return xml;
}
function handleSkills() {
var xml = prepareXML();
var url = "XMLServlet?timeStamp" + new Date().getTime();
createXMLHttpRequest();
xmlHttp.onreadystatechange = handleStateChange;
xmlHttp.open("POST", url);
xmlHttp.setRequestHeader("Content-Type", "text/xml");
xmlHttp.send(xml);
}
在上例中,将客户端于多选单中选择的数据,以下列的XML格式送出:
<skills>
<skill>java</skill>
<skill>vb</skill>
<skill>csharp</skill>
</skills>
而伺服端接收到XML之后,针对XML加以剖析,取得每个节点数据,如果使用Servlet作为伺服端,可以使用org.w3c下所提供的DOM操作相关 类别来剖析XML的内容,例如在以下的XMLServlet中,将取得的XML加以剖析,并以另一个XML文件重新发送回客户端。
• XMLServlet.java
package onlyfun.caterpillar;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
public class XMLServlet extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String xml = readXMLFromRequestBody(request);
Document xmlDoc = null;
try {
DocumentBuilder builder =
DocumentBuilderFactory.newInstance().newDocumentBuilder();
xmlDoc = builder.parse(
new ByteArrayInputStream(xml.getBytes()));
}
catch(ParserConfigurationException e) {
System.out.println(e);
}
catch(SAXException e) {
System.out.println(e);
}
String responseXML = prepareXMLResponse(xmlDoc);
responseXML = responseXML + "</responses>";
response.setContentType("text/xml");
response.getWriter().print(responseXML);
}
private String readXMLFromRequestBody(HttpServletRequest request){
StringBuffer xml = new StringBuffer();
try {
BufferedReader reader = request.getReader();
String line = null;
while((line = reader.readLine()) != null) {
xml.append(line);
}
}
catch(Exception e) {
System.out.println("XML读取有误…" + e.toString());
}
return xml.toString();
}
private String prepareXMLResponse(Document xmlDoc) {
NodeList selectedSkills = xmlDoc.getElementsByTagName("skill");
StringBuffer xml = new StringBuffer();
xml.append("<responses>");
for(int i = 0; i < selectedSkills.getLength(); i++) {
String skill = selectedSkills.item(i).getFirstChild().getNodeValue();
xml.append("<response>");
xml.append(skill);
xml.append("</response>");
}
return xml.toString();
}
}
这个Servlet只是简单的示范如何剖析XML,并重新使用以下的XML格式,将选择的数据发送回客户端:
<response>
<response>java</response>
<response>vb</response>
<response>csharp</response>
</response>
将数据以新的XML格式发送回客户端,纯綷只是要示范客户端取得XML文件时,如果加以剖析处理,客户端接收到的资料如果是XML文件,则可以使用XMLHttpRequest的responseXML属性,尝试取得代表XML文件的DOM对象,之后就可以利用DOM的各种操作方法来剖析文件内容,例如:
function handleStateChange() {
if(xmlHttp.readyState == 4) {
if(xmlHttp.status == 200) {
var xmlDoc = xmlHttp.responseXML; // 取得DOM对象
var responses = xmlDoc.getElementsByTagName("response");
var out = "Responses: ";
for(var i = 0; i < responses.length; i++) {
var response = responses[i];
out = out + "<br/><b>" + response.childNodes[0].nodeValue + "</b>";
}
document.getElementById("response").innerHTML = out;
}
}
}
在这边您所看到的三段JavaScript片段,组成HandleXMLEx-1.js,可以搭配以下的HTML来完成一个完整的客户端/伺服端程序:
• HandleXMLEx-1.html
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=BIG5">
<title>处理XML</title>
<script type="text/javascript" src="HandleXMLEx-1.js"></script>
</head>
<body>
<select id="skills" size="5" multiple="true">
<option value="c">C 语言</option>
<option value="cpp">C++</option>
<option value="java">Java</option>
<option value="csharp">C#</option>
<option value="vb">VB</option>
</select>
<br>
<input type="button" value="送出" οnclick="handleSkills();"/>
<br>
<div id="response"></div>
</body>
</html>
如果执行这个程序,客户端所选择的数据以XML送出,伺服端加以剖析,并以另一个XML传回,客户端再剖析XML并显示卷标中的文字,这是一个基本的XML传送与接收的例子。