SSH实战 · AJAX异步校验

时间:2024-01-12 15:46:02
前台JS代码
/*异步验证用户名的输入格式以及是否存在*/
function CheckUsername(){
     /*取到用户名输入框*/
     var nametxt = document.getElementById("username");
     /*获取输入的用户名值*/
     var username = nametxt.value;
     /*获取到装错误信息的span框*/
     var sp = document.getElementById("usernameError");
     var regex = /^[a-z0-9]{4,12}$/i;
     /*创建异步函数*/
     var xhr = createXmlHttp();
     /*设置监听*/
     xhr.onreadystatechange = function()
     {
          if(xhr.readyState == 4){
              if(xhr.status == 200){
                   /*为信息提示框赋文本*/
                   sp.innerHTML = xhr.responseText;
                   /*为信息提示框赋样式*/
                   sp.className = "infoError";
              }
          }
     }
     /*打开链接 · 不加时间戳则会引起浏览器的缓存*/
     xhr.open("GET", "${pageContext.request.contextPath}/user_FindByName.action?time="+new Date().getTime()+"&username="+username, true);
     /*发送*/
     xhr.send();
}
function createXmlHttp(){
     var xmlHttp;
     try{//Firefox, Opera8.0+, Safari
          xmlHttp = new XMLHttpRequest();
     } catch(e){
          try {//IE
              xmlHttp = new ActiveXObject("Msxm12.XMLHTTP");
          } catch (e) {}
     }
     return xmlHttp;
}
后台action代码
     /**
     * AJAX异步校验用户名
     * @return String
     * @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>");
          }
          /*AJAX操作,不需要页面跳转*/
          return NONE;
     }