1.register.html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>register.html</title>
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="this is my page">
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<!--<link rel="stylesheet" type="text/css" href="./styles.css">-->
<script type="text/javascript">
var xmlHttp = null;
//声明XMLHttpRequest对象函数
function getXMLHttp()
{
try{
//fireFox、Opera、Safari
xmlHttp = new XMLHttpRequest();
}catch(e){
try{
//IE6.0+
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
}catch(e){
try{
//IE5.5+
xmlHttp = xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}catch(e){
alert("你的浏览器不支持AJAX!");
return false;
}
}
}
return xmlHttp;
}
//验证函数
function check()
{
var userName = document.getElementById("username").value;
var xmlHttp = getXMLHttp();
xmlHttp.open("POST","CheckAction?tt="+Math.random(),true);
xmlHttp.onreadystatechange = handleResult;
xmlHttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlHttp.send("username="+userName);
}
//返回结果处理
function handleResult()
{
if(xmlHttp.readyState == 4)
{
if(xmlHttp.status == 200)
{
document.getElementById("nameInfo").innerHTML = xmlHttp.responseText;
}
}
}
</script>
</head>
<body>
<form name="form1"></form>
<table>
<tr>
<td>用户名:</td>
<td><input type="text" id="username" οnblur="check()"><span id="nameInfo"></span></td>
</tr>
<tr>
<td>密码:</td>
<td><input type="text" name="password" οnblur="check()"><span id="pwdInfo"></span></td>
</tr>
</table>
</body>
</html>
2.Servlet
public class CheckAction extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
// TODO Auto-generated method stub
this.doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
resp.setContentType("text/html;charset=GBK");
PrintWriter out = resp.getWriter();
String username = req.getParameter("username");
System.out.println(username);
if(username.trim().length()==0 || username == null){
out.println("<font color='red'>用户名不能为空!</font>");
}else if(username.equals("ajax")){
out.println("<font color='blue'>此用户名已经被注册!</font>");
}else{
out.println("<font color='green'>此用户名可以使用!</font>");
}
}
}
注意::
从上述代码中可以看出获得XMLHttpRequest实例的代码片段
function getXMLHttp()
{
try{
//fireFox、Opera、Safari
xmlHttp = new XMLHttpRequest();
}catch(e){
try{
//IE6.0+
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
}catch(e){
try{
//IE5.5+
xmlHttp = xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}catch(e){
alert("你的浏览器不支持AJAX!");
return false;
}
}
}
return xmlHttp;
}