书上的例子,稍作修改,贴上来。
html文件写的是js脚本和输入框,servlet做验证
html->servlet:通过xmlHttp.open("GET","servlet/UserNameCheck?username=" + document.userform.username.value,true);
servlet->html:xmlHttp.responseText
TestAjax3.html
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>TestAjax3</title>
<script type="text/javascript">
var xmlHttp;
function createXMLHttp(){
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;
}
}
}
nextToDo();
}
function nextToDo(){
xmlHttp.onreadystatechange = function(){
if(xmlHttp.readyState == 4){
document.getElementById("usermsg").innerHTML="<font color=blue>"+xmlHttp.responseText+"</font>";
}
};
xmlHttp.open("GET","servlet/UserNameCheck?username=" + document.userform.username.value,true);
//System.out.println(request.getParameter("message"));
xmlHttp.send(null);
}
</script>
</head>
<body>
<form action="" name="userform">
输入:<input type="text" name="username" οnblur="createXMLHttp();">
<span id="usermsg"></span><br/>
<input type="submit" value="提交">
</form>
</body>
</html>
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class UserNameCheck extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
ArrayList<String> usernames = new ArrayList<String>();
usernames.add("fdsv1");
usernames.add("flys");
usernames.add("bfdsa");
response.setContentType("text/xml; charset=UTF-8");//设置响应文本格式
response.setHeader("Cache-Control", "no-cache"); //设置没有缓存
PrintWriter out = response.getWriter(); //获得输出流
String username = request.getParameter("username");//获得username参数
boolean flag = false; //初始化变量falg
for(String uname : usernames){ //遍历所有的用户名
if(uname.equals(username)){
flag = true;
break;
}
}
String message;
if(flag) { //如果flag为true
//message="该用户名已经被占用,请重新输入!";
message="√";
out.println(message);
}else {
//如果flag为false
//message="该用户名可以使用!";
message="X";
out.println(message);
}
request.setAttribute("message", message);
out.flush(); //刷新输出流
out.close(); //关闭输出流
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response); //调用doGet方法
}
}