基于jQuery实现的Ajax 验证用户名唯一性

基于jQuery实现的Ajax 验证用户名唯一性

前端jsp页面代码 

1 <tr>
2                                     <th><span class="requiredField">*</span>用户名:</th>
3                                     <td><input type="text" id="username" name="username"
4                                         onblur="checkName()" class="text" maxlength="20"><span
5                                             id="tishi"></span></td>
6                                 </tr>

script 代码 

 1 <script type="text/javascript">
 2 
 3     function checkName() {
 4         var username = $("#username").val();
 5         //获取账号后的提示信息文本
 6         var tishi = document.getElementById("tishi");
 7         $.ajax({
 8             url : "${pageContext.request.contextPath}/user_findByUsername.action", //后台查询验证的方法
 9             data : {
10                 "username" : username
11             }, //携带的参数
12             type : "post",
13             success : function(msg) {
14                 //根据后台返回前台的msg给提示信息加HTML
15                 if ("true" != msg) {
16                     // 账号已经存在
17                     tishi.innerHTML = "<font color='red'>抱歉," + username + "已被注册,请更换!</font>"
18                 } else {
19                     // 账号不存在
20                     tishi.innerHTML = "<font color='green'>恭喜," + username + " 可以注册!</font>"
21                 }
22             }
23         });
24 
25     }
26 </script>

其中UserAction中的代码 

 1 public String findByUsername() throws IOException{
 2         User u=userService.findByUsername(user.getUsername());
 3           String result = "true";
 4           if (u!=null ) {
 5               //说明账号存在
 6               result = "false";
 7           }
 8           //输出到界面
 9           HttpServletResponse response = ServletActionContext.getResponse();
10           response.setContentType("text/html");
11           ServletOutputStream outputStream = response.getOutputStream();
12           outputStream.write(result.getBytes());
13           outputStream.close();
14         return NONE;
15     }

Userservice中的代码 

1 public User findByUsername(String username) {
2         return userDao.findByUsername(username);
3     }

UserDaoImpl中的代码 

1     public User findByUsername(String username) {
2         List<User> list=(List<User>) this.getHibernateTemplate().find("from User where username=?",username);
3         if(list!=null&&list.size()>0){
4             return list.get(0);
5         }
6         return null;
7     }

即可实现异步刷新 

 

posted @ 2017-12-12 20:50  Kmily_Lee  阅读(5727)  评论(0编辑  收藏  举报