---AjaxTest.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;
/**
* @时间: Nov 14, 2008 1:27:38 PM
* @类说明:
*/
public class AjaxTest extends HttpServlet
{
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException
{
String str = request.getParameter("status");
response.setContentType("text/html; charset=GBK");
response.getOutputStream().print(str);
}
}
--test.jsp---
<%@ page language="java" import="java.util.*" pageEncoding="GBK"%>
<%
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>
<script type="text/javascript">
var http_request = false;
function send_request(url)
{//初始化、指定处理函数、发送请求的函数
http_request = false;
//开始初始化XMLHttpRequest对象
if(window.XMLHttpRequest)
{ //Mozilla 浏览器
http_request = new XMLHttpRequest();
if(http_request.overrideMimeType)
{//设置MiME类别
http_request.overrideMimeType('text/xml');
}
}
else if(window.ActiveXObject)
{ // IE浏览器
try
{
http_request = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e)
{
try
{
http_request = new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e){}
}
}
if(!http_request)
{ // 异常,创建对象实例失败
window.alert("不能创建XMLHttpRequest对象实例.");
return false;
}
http_request.onreadystatechange = function(){ processRequest() } ;
//alert('request');
// 确定发送请求的方式和URL以及是否同步执行下段代码
http_request.open("POST", url, true);
//alert('url的值: '+url);
http_request.send(null);
}
function processRequest()
{
if (http_request.readyState == 4)
//检测请求状态http_request.readyState有以下几种状态 0 (未初始化) 1 (正在装载) 2 (装载完毕) 3 (交互中) 4 (完成)
{ // 判断对象状态
if (http_request.status == 200)
{ // 信息已经成功返回,开始处理信息
var divhtml = http_request.responseText;
// 设置状态ffdsafdsaf
document.getElementById("userId").value=divhtml;
// document.getElementById("userId").innerHTML=divhtml;
// alert('--');
}
}
}
function getTopic()
{
send_request('<%=path%>/ajaxTest?status=上传成功!!');
}
</script>
</head>
<body>
<input id=userId type=text value=nokia οnchange="getTopic()"></input>
</body>
</html>
---web.xml---
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4"
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">
<servlet>
<servlet-name>ajaxTest</servlet-name>
<servlet-class>com.AjaxTest</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ajaxTest</servlet-name>
<url-pattern>/ajaxTest</url-pattern>
</servlet-mapping>
</web-app>