实例
以下是我所写的一个简单的例子
:
一、
ajaxServlet.java
程序清单
:
package com;
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;
/*
*------------------------------------------------------
*
文件名: ajaxServlet.java
*
创建日期: 2005-10-25
*
原作者: miaohai
*
版权所有: miaohai
*
功能说明: 生成XML文档
*
*
修改记录:N/A
*------------------------------------------------------
*/
public class ajaxServlet extends HttpServlet{
private static final String CONTENT_TYPE="text/xml; charset=gb2312";
public void init() throws ServletException{
}
public void doGet(HttpServletRequest request,HttpServletResponse response)
throws ServletException,IOException{
response.setContentType(CONTENT_TYPE);
PrintWriter out=response.getWriter();
String action=request.getParameter("action");
if(("send").equals(action)){
StringBuffer sb=new StringBuffer("");
sb.append("<type_name>AA</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("</type>");
out.write(sb.toString());
out.close();
}
}
}
二、
html
页面
:
<html>
<head>
<title>AJAX.html</title>
</head>
<script type="text/javascript">
/*
通过异步传输
XMLHTTP
发送参数到
ajaxServlet
,返回符合条件的
XML
文档
*/
function getResult(){
var url = "/Test/ajaxServlet?action=send";
if (window.XMLHttpRequest) {
req = new XMLHttpRequest();
}else if (window.ActiveXObject){
req = new ActiveXObject("Microsoft.XMLHTTP");
}
if(req){
req.open("GET",url, true);
req.onreadystatechange = complete;
req.send(null);
}
}
/*
分析返回的XML文档*/
function complete(){
if (req.readyState == 4){
if (req.status == 200) {
var type = req.responseXML.getElementsByTagName("type_name");
var str=new Array();
for(var i=0;i< type.length;i++){
str[i]=type[i].firstChild.data;
document.all['td'].innerHTML+=str[i]+"
";
}
}
}
}
</script>
<body onLoad="getResult()">
<table width="80%" border="0" cellspacing="0" cellpadding="0">
<tr><td id="td"> </td></tr>
</table>
</body>
三、
web.xml
文件
<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
version="2.4">
<servlet>
<servlet-name>ajaxServlet</servlet-name>
<servlet-class>com.ajaxServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ajaxServlet</servlet-name>
<url-pattern>/ajaxServlet</url-pattern>
</servlet-mapping>
</web-app>
四、运行图: