1.新建工程ajax_demo01
2.在src下面新建一个包com.ajax.test并在这个包下新建一个servlet
AjaxTest.java
package com.ajax.test;
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 AjaxTest extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request,response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
String name=request.getParameter("name");
if(name!=null)
{
out.println("error");
}else
{
out.println("success");
}
}
}
然后在WebRoot下面新建一个文件夹js在这个文件夹新建一个文件
verify.js
var req; //定义变量,用来创建xmlhttprequest对象
function creatReq() // 创建xmlhttprequest,ajax开始
{
// var url="servlet/AjaxTest"; //要请求的服务端地址
if(window.XMLHttpRequest) //非IE浏览器,用xmlhttprequest对象创建
{
req=new XMLHttpRequest();
}
else if(window.ActiveXObject) //IE浏览器用activexobject对象创建
{
req=new ActiveXObject("Microsoft.XMLHttp");
}
if(req) //成功创建xmlhttprequest
{
var userName=document.getElementById("userName").value;
req.open("GET","servlet/AjaxTest?name"+userName,true); //与服务端建立连接(请求方式post或get,地址,true表示异步)
req.onreadystatechange = callback; //指定回调函数,的属性名不能加括号
req.send(null); //发送请求
}
}
function callback() //回调函数,对服务端的响应处理,监视response状态
{
if(req.readystate==4) //请求状态为4表示成功
{
if(req.status==200) //http状态200表示OK
{
Dispaly(); //所有状态成功,执行此函数,显示数据
}
else //http返回状态失败
{
alert("服务端返回状态" + req.statusText);
}
}
else //请求状态还没有成功,页面等待
{
document .getElementById ("result").innerHTML ="数据加载中";
}
}
function Dispaly() //接受服务端返回的数据,对其进行显示
{
document .getElementById ("result").innerHTML =req.responseText;
}
最后在你的主页面index.jsp编写一个简单的验证
<%@ page language="java" pageEncoding="UTF-8"%>
<%
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>
<base href="<%=basePath%>">
<title>ajax测试实例一</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
<script language="javascript" src="js/verify.js" charset="utf-8"></script>
</head>
<body>
<h1>ajax测试实例一</h1>
<hr>
<br/>
<input type="text" id="userName">
<input type="submit" value="检验" οnclick="creatReq()">
<span id="result"></span>
</body>
</html>