jsp页面
<%@ page language="java" import="java.util.*" pageEncoding="gbk"%>
<%
request.setCharacterEncoding("GBK");
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Ajax</title>
<script type="text/javascript" language="JavaScript">
var xmlHttp;
function createXMLHttpRequest()
{
try{
xmlHttp=new XMLHttpRequest();
}
catch(e)
{
try
{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e)
{
try
{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e)
{
alert('您的浏览器不支持Ajax!');
return false;
}
}
}
}
function sendRequest(url)
{
createXMLHttpRequest();
xmlHttp.open("GET",url,true);
xmlHttp.onreadystatechange=processResponse;
xmlHttp.send(null);
}
function processResponse()
{
if(xmlHttp.readyState==4)
{
if(xmlHttp.status==200)
{
var res=xmlHttp.responseText;<%-- xmlHttp.responseXML.getElementsByTagName("res")[0].firstChild.data;--%>
window.alert(res);
}
else
{
window.alert("你请求的页面出现异常!");
}
}
}
function singUp()
{
var name=document.getElementById('username').value;
var psw=document.getElementById('pwd').value;
sendRequest('servlet/Ajax?uname='+name+'&pwd='+psw);
}
</script>
</head>
<body>
<form name="myForm" method="post" >
用户:<input id="username" name="username" type="text" /><br>
密码:<input id="pwd" type="password" name="pwd"><br>
<input type="button" value="测试" οnclick="singUp();">
</form>
</body>
</html>
AjaxServlet
package com.ajax;
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;
public class Ajax extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("gbk");
response.setContentType("text/xml;charset=gbk");
response.setHeader("Cache-Control","no-cache");
String name=request.getParameter("uname");
String pwd=request.getParameter("pwd");
PrintWriter out=response.getWriter();
if("name".equals(name)||"pwd".equals(pwd))
{
out.println("测试成功");
}else
{
out.println("测试失败");
}
}
}
webxml
<?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>
<description>This is the description of my J2EE component</description>
<display-name>This is the display name of my J2EE component</display-name>
<servlet-name>Ajax</servlet-name>
<servlet-class>com.ajax.Ajax</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Ajax</servlet-name>
<url-pattern>/servlet/Ajax</url-pattern>
</servlet-mapping>
</web-app>