檔案: XMLservlet.java
package servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.*;
import javax.xml.transform.dom.*;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
public class XMLServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String CONTENT_TYPE = "text/xml; charset=gb2312";
response.setContentType(CONTENT_TYPE);
PrintWriter out = response.getWriter();
StringBuffer sb = new StringBuffer("<address>");
sb.append("<type_name>AAhl</type_name>");
sb.append("<type_name>BB</type_name>");
sb.append("<type_name>CC</type_name>");
sb.append("<type_name>DD</type_name>");
sb.append("</address>");
out.write(sb.toString());
out.close();
}
}
///////////////////////////
讀取XMLservlet.java發送的 xml檔案的 myAjax.jsp
<%@ page language="java" import="java.util.*" pageEncoding="GBK"%>
<html>
<head>
<script language="javascript">
var xmlHttp;
function createXMLHttp(){
if(window.XMLHttpRequest){
xmlHttp = new XMLHttpRequest();
}else{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
}
//到這裡都是為了擷取得到XMLHttpRequest對象
function getInfo(){
createXMLHttp();
xmlHttp.open("POST", "servlet/XMLServlet"); //建立到伺服器的資料請求,這裡請求一個名為“allarea.xml”檔案
xmlHttp.onreadystatechange = getCityCallback ; //一個回呼函數
xmlHttp.send(null); //想伺服器發送的資料
}
function getCityCallback(){
if(xmlHttp.readyState == 4 ){
if(xmlHttp.status == 200){ //這裡的倆個if語句是為了判斷 請求是否已經完成
var allareaHLp = xmlHttp.responseText;
alert(allareaHLp);
var type = xmlHttp.responseXML.getElementsByTagName("type_name");
alert("---------");
var str=new Array();
for(var i=0;i<type.length;i++){
str[i]=type[i].firstChild.data;
alert(str[i]);
document.all['td'].innerHTML+=str[i]+"<BR>";
}
}
}
}
</script>
</head>
<body onload = "getInfo()">
<table width="80%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td id="td">
</td>
</tr>
</table>
</body>
</html>
關鍵是在servlet中產生 xml檔案資料