jQuery Ajax实现无刷新用户名验证
最近看到了jQuery 的ajax实现,想到了这个功能并写了下来。 简略代码如下:
1、reg.jsp
<%@ page language="java" contentType="text/html;charset=utf-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>jQuery ajax</title>
<script type="text/javascript" src="resources/js/jquery-1.1.3.pack.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#uName").change(function(){
$.post("register.do", { name: $("#uName").val()} ,function(data){$("#output").text(data);});
});
});
</script>
</head>
<body>
<div id="reg">
<font size="4" color="blue"><b>注册</b></font>
<form name="form1" action="" method="post">
用户名:<input type="text" name="uName" id="uName"> <font id="output"></font><p>
</form>
</div>
</body>
</html>
2、RegisterAction.java
package com.demo.action;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
public class RegisterAction extends Action {
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response){
// TODO Auto-generated method stub
response.setCharacterEncoding("utf-8");
response.setHeader("Charset","utf-8");
response.setHeader("Cache-Control", "no-cache");
try {
PrintWriter out = response.getWriter();
String username = request.getParameter("name").trim();
//例子中未使用数据库。。。
System.out.println(username+"--------------------");
if(username.equals("kong")){
out.println("用户名已存在!");
return null;
}
if(username==null & username==""){
out.println("用户名不能为空!");
return null;
}
if(username.length()<4){
out.println("用户名为4-16位的数字或字母!");
return null;
}else{
out.println("ok!!");
return null;
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
ok,代码到此结束。是不是很简单!!
注意一点,要配上过滤器,不然会有乱码!!