<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
var xmlHttpRequest=null;
//创建Ajax引擎
function getXmlHttpRequest() {
if (window.ActiveXObject) {
//ie
xmlHttpRequest = new ActiveXObject("Microsoft.XMLHTTP");
} else {
//firefox
xmlHttpRequest = new XMLHttpRequest();
}
}
//检查用户名是否重复
function checkUserName() {
//创建ajax引擎
getXmlHttpRequest();
//如果ajax引擎创建成功
if (xmlHttpRequest) {
//第一个参数表示请求的方式get/post
//第二个参数指定url
//第三个参数true表示使用异步机制
//如果使用get方法请求,第一次进行请求,第二次从缓存里面取
// var url = "/Ajax/CheckUserName?username="+$("username").value;
var url = "/Ajax/CheckUserName";
//post提交数据
var data="username="+$("username").value;
//xmlHttpRequest.open("get", url, true);
xmlHttpRequest.open("post", url, true);
xmlHttpRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
//回调函数
xmlHttpRequest.onreadystatechange =chuli;
//发送请求,如果是get,写null, 可以传参数
//xmlHttpRequest.send(null);
xmlHttpRequest.send(data);
}
}
//回调函数
function chuli() {
if (xmlHttpRequest.readyState == 4) {
$("res").innerHTML=xmlHttpRequest.responseText;
}
}
//$方法
function $(id) {
return document.getElementById(id);
}
</script>
</head>
<body>
用户名:(输入aaa重复)
<input type="text" id="username" οnkeyup="checkUserName();" />
<span id="res" style="color: red;"></span>
</body>
</html>
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Writer;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class CheckUserName
*/
@WebServlet("/CheckUserName")
public class CheckUserName extends HttpServlet {
private static final long serialVersionUID = 1L;
public CheckUserName() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html; charset=utf-8");
response.setHeader("Cache-Control", "no-cache");
PrintWriter out=response.getWriter();
String username=request.getParameter("username");
if(username.equals("aaa")){
out.print("GET:用户名重复");
}else{
out.print("GET:用户名可以使用");
}
out.close();
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
resp.setContentType("text/html; charset=utf-8");
resp.setHeader("Cache-Control", "no-cache");
PrintWriter out=resp.getWriter();
String username=req.getParameter("username");
if(username.equals("aaa")){
out.print("POST:用户名重复");
}else{
out.print("POST:用户名可以使用");
}
out.close();
}
}