使用Ajax完成用户名异步校验
web开发中我们常常要保证用户在注册时要使用不同的用户名,此时在注册表单中就要用Ajax完成用户名异步校验,以下是相关代码。本实例用的是SSH框架,请多指教。
要在用户名的input域添加onblur事件,本例中是οnblur=”checkUsername()”
注册form表单:
<form action="${ pageContext.request.contextPath }/user_regist.action" method="post" novalidate="novalidate" onsubmit="return checkForm();">
<!--用户名-->
<input type="text" id="username" name="username" class="text" maxlength="20" onblur="checkUsername()"/>
<span id="span1"></span>
<input type="submit" class="submit" value="注册">
</form>
js和Ajax脚本,含密码校验:
校验时将请求发送到后台Struts的user_findByName.action,并加了时间戳防止浏览器缓存。
<script> function checkForm(){ // 校验用户名: // 获得用户名文本框的值: var username = document.getElementById("username").value; if(username == null || username == ''){ alert("用户名不能为空!"); return false; } // 校验密码: // 获得密码框的值: var password = document.getElementById("password").value; if(password == null || password == ''){ alert("密码不能为空!"); return false; } // 校验确认密码: var repassword = document.getElementById("repassword").value; if(repassword != password){ alert("两次密码输入不一致!"); return false; } } function checkUsername(){ // 获得文件框值: var username = document.getElementById("username").value; // 1.创建异步交互对象 var xhr = createXmlHttp(); // 2.设置监听 xhr.onreadystatechange = function(){ if(xhr.readyState == 4){ if(xhr.status == 200){ //将校验信息写回到用户名的input域后面 document.getElementById("span1").innerHTML = xhr.responseText; } } } // 3.打开连接,加上时间戳,防止浏览器缓存new Date().getTime() xhr.open("GET","${pageContext.request.contextPath}/user_findByName.action?time="+new Date().getTime()+"&username="+username,true); // 4.发送 xhr.send(null); } function createXmlHttp(){ var xmlHttp; try{ // Firefox, Opera 8.0+, Safari xmlHttp=new XMLHttpRequest(); } catch (e){ try{// Internet Explorer xmlHttp=new ActiveXObject("Msxml2.XMLHTTP"); } catch (e){ try{ xmlHttp=new ActiveXObject("Microsoft.XMLHTTP"); } catch (e){} } } return xmlHttp; } </script>
DAO代码:
public class UserDao extends HibernateDaoSupport {
// 按名次查询是否有该用户:
public User findByUsername(String username) {
String hql = "from User where username = ?";
List<User> list = this.getHibernateTemplate().find(hql, username);
if (list != null && list.size() > 0) {
return list.get(0);
}
return null;
}
}
service代码:
@Transactional
public class UserService {
// 按用户名查询用户的方法:
public User findByUsername(String username){
return userDao.findByUsername(username);
}
}
action负责调用service中的方法根据用户名去数据库查找相应的对象,若能找到说明该用户名已经被注册过,不能再使用,若找不到说明该用户名未被注册,可以使用。使用response将信息返回到前台。
action代码:
public class UserAction extends ActionSupport implements ModelDriven<User> {
// 模型驱动使用的对象
private User user = new User();
public User getModel() {
return user;
}
/** * AJAX进行异步校验用户名的执行方法 * * @throws IOException */
public String findByName() throws IOException {
// 调用Service进行查询:
User existUser = userService.findByUsername(user.getUsername());
// 获得response对象,项页面输出:
HttpServletResponse response = ServletActionContext.getResponse();
response.setContentType("text/html;charset=UTF-8");
// 判断
if (existUser != null) {
// 查询到该用户:用户名已经存在
response.getWriter().println("<font color='red'>用户名已经存在</font>");
} else {
// 没查询到该用户:用户名可以使用
response.getWriter().println("<font color='green'>用户名可以使用</font>");
}
return NONE;
}
}
实体类User:
/** * 用户名模块实体类: * @author zhk *CREATE TABLE `user` ( `uid` int(11) NOT NULL AUTO_INCREMENT, `username` varchar(255) DEFAULT NULL, `password` varchar(255) DEFAULT NULL, `name` varchar(255) DEFAULT NULL, `email` varchar(255) DEFAULT NULL, `phone` varchar(255) DEFAULT NULL, `addr` varchar(255) DEFAULT NULL, `state` int(11) DEFAULT NULL, `code` varchar(64) DEFAULT NULL, PRIMARY KEY (`uid`) ) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8; */
public class User {
private Integer uid;
private String username;
private String password;
private String name;
private String email;
private String phone;
private String addr;
private Integer state;
private String code;
// 一个用户对应多个订单:
private Set<Order> orders = new HashSet<Order>();
public Integer getUid() {
return uid;
}
public void setUid(Integer uid) {
this.uid = uid;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getAddr() {
return addr;
}
public void setAddr(String addr) {
this.addr = addr;
}
public Integer getState() {
return state;
}
public void setState(Integer state) {
this.state = state;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public Set<Order> getOrders() {
return orders;
}
public void setOrders(Set<Order> orders) {
this.orders = orders;
}
}
实体类的映射:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="cn.edu.imau.shop.user.vo.User" table="user">
<id name="uid">
<generator class="native"/>
</id>
<property name="username"/>
<property name="password"/>
<property name="name"/>
<property name="email"/>
<property name="phone"/>
<property name="addr"/>
<property name="state"/>
<property name="code"/>
<set name="orders" cascade="delete">
<key column="uid"/>
<one-to-many class="cn.edu.imau.order.vo.Order"/>
</set>
</class>
</hibernate-mapping>
到此就完成了使用Ajax对用户名的异步校验。敬请指正。