XML傳送與接收

<script>function StorePage(){d=document;t=d.selection?(d.selection.type!='None'?d.selection.createRange().text:''):(d.getSelection?d.getSelection():'');void(keyit=window.open('http://www.365key.com/storeit.aspx?t='+escape(d.title)+'&u='+escape(d.location.href)+'&c='+escape(t),'keyit','scrollbars=no,width=475,height=575,left=75,top=20,status=no,resizable=yes'));keyit.focus();}</script>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="送出" onclick="handleSkills();"/>

<br>
<div id="response"></div>
</body>
</html>

如果執行這個程式,客戶端所選擇的資料以XML送出,伺服端加以剖析,並以另一個XML傳回,客戶端再剖析XML並顯示標籤中的文字,這是一個基本的XML傳送與接收的例子。

你可能感兴趣的:(JavaScript,xml,Ajax,servlet,vb)