24H免费课程咨询  TEL:13401595960   QQ:1870218756  微信:13401595960(李老师)

东方博宜

网站首页 > 软件开发资讯 > Java开发

Ajax校验用户名是否重复

2017-07-19 20:20:29 东方博宜 阅读

1ajax:异步的JavaScriptXML技术

异步:无刷新的数据获取和校验技术!

应用场景:离开输入框检验用户名是否重复、多级城市联动下拉菜单!

Ajax使用的核心的对象:XMLHttpRequest

 

参考:http://www.w3school.com.cn/ajax/index.asp

 

由于向后台发送数据到后台反馈数据到前端有一定的时间差,因此要等到后台响应完毕才能获取响应的数据!

 

onreadystatechange存储函数(或函数名),每当 readyState 属性改变时,就会调用该函数。

 

readyState存有 XMLHttpRequest 的状态。从 0 4 发生变化。

0: 请求未初始化

1: 服务器连接已建立

2: 请求已接收

3: 请求处理中

4: 请求已完成,且响应已就绪

 

status:后台是否存在的状态

200: "OK"

404: 未找到页面

 

index.jsp

  <style type="text/css"> 

     .error{

        color:#F00;

     }

    

     .errorinput{

        border:1px solid #F00;

        background-color:pink;

     }

  </style>

    用户名:<input type="text" name="username" id="username" onblur="checkName()"/>

    <span id="msg" class="error"></span>

   

   <script type="text/javascript">

      //ajax校验

      var xmlhttp;//核心对象

  

      //校验用户名

      function checkName(){

          //获取用户名输入框

          var username = document.getElementById("username");

          //获取提示信息的span

          var msg = document.getElementById("msg");

         

          var regnull = /^[ ]*$/;

          //如果填写了,且不是空格,则ajax校验

          if(regnull.test(username.value) == false){

              msg.innerHTML = "";

              //如果是主流浏览器IE7+ 火狐 谷歌……

              if(window.XMLHttpRequest){

                  xmlhttp = new XMLHttpRequest();

              }else{

                  xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");

              }

             

              //准备发送的url

              var url = "CheckNameServlet?name=" + username.value;

              //打开发送通道(get表示get带参数,true表示是异步请求)

              xmlhttp.open("GET",url,true);

              //监测向后台发数据直到响应的整个过程

              xmlhttp.onreadystatechange = callBack;

              xmlhttp.send();//发送数据

          }else{

             msg.innerHTML = "请输入用户名";

          }

      }

     

      //状态发生改变时的回调函数

      function callBack(){

          //获取提示信息的span

          var msg = document.getElementById("msg");

         

          //获取状态 xmlhttp.status表示后台是否可访问的状态200表示可访问,404表示访问不到

          //alert(xmlhttp.readyState + " " +xmlhttp.status);

          if(xmlhttp.readyState == 4 && xmlhttp.status == 200){

              var r = xmlhttp.responseText;//获取响应文本

              //页面显示结果

              if(r == "used"){

                  msg.innerHTML = "该用户名已被占用,请尝试其他用户名";

              }else if(r == "useable"){

                  msg.innerHTML = "<span style='color:green'>用户名可用</span>";

              }else if(r == "noparam"){

                  msg.innerHTML = "参数错误,请刷新重试";

              }

          }else{

             msg.innerHTML = "检验中,请稍后……";

          }

      }

   </script>

 

CheckNameServlet

public class CheckNameServlet extends HttpServlet {

 

        

         public void doGet(HttpServletRequest request, HttpServletResponse response)

                            throws ServletException, IOException {

         this.doPost(request, response);              

         }

 

        

         public void doPost(HttpServletRequest request, HttpServletResponse response)

                            throws ServletException, IOException {

 

                   response.setContentType("text/html;charset=utf-8");

                   request.setCharacterEncoding("utf-8");

                   PrintWriter out = response.getWriter();

                  

                   //获取参数

                   String name = request.getParameter("name");

                   //对中文转码

                  if(name != null){

                            name = new String(name.getBytes("iso8859-1"),"utf-8");

                      

                            //如果是admin或者管理员表示占用,否则没有占用

                            if(name.equals("admin") || name.equals("管理员")){

                                     out.print("used");//千万不要写println否则会产生一个回车符,导致js判断出错

                            }else{

                                     out.print("useable");

                            }

                   }else{

                            out.print("noparam");

                   }

                  

                   out.flush();

                   out.close();

         }

 

}

 

 

 

IE浏览器存在的几个问题:

Aajax  get带中文IE会乱码

解决办法:对get传递的中文采用encodeURI函数进行编码后传递!

图片.png


B、如果IE在页面不刷新的情况下,向后台传递同一个参数,第一次会传递,后面再传递IE会直接获取第一次判断的结果,不会再真正传递了!(缓存问题)

解决办法:向后台传递参数时,携带一个随机数,使得每次向后台传递的参数都有差异,让IE认为每次带的参数都不一样,IE就会每次都提交到后台!

图片.png

 

xmlhttp变量重复赋值的问题:

每离开一次输入框,都会调用checkName函数,而每次调用checkName函数都要生成XMLHttpRequest对象,造成对象的重复生成!

 

解决办法:在为xmlhttp核心对象赋值的地方,添加判断,如果xmlhttp没有值,再赋值,有值,不赋值!

 

图片.png


优化后的代码:

index.jsp

  <style type="text/css"> 

     .error{

        color:#F00;

     }

    

     .errorinput{

        border:1px solid #F00;

        background-color:pink;

     }

  </style>

    用户名:<input type="text" name="username" id="username" onblur="checkName()"/>

    <span id="msg" class="error"></span>

   

   <script type="text/javascript">

      //ajax校验

      var xmlhttp = null;//核心对象

     

      //为核心对象xmlhttp赋值

      function init(){

           if(xmlhttp == null){

              //如果是主流浏览器IE7+ 火狐 谷歌……

              if(window.XMLHttpRequest){

                  xmlhttp = new XMLHttpRequest();

              }else{

                  xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");

              }

           }

      }

  

      //校验用户名

      function checkName(){

          //获取用户名输入框

          var username = document.getElementById("username");

          //获取提示信息的span

          var msg = document.getElementById("msg");

         

          var regnull = /^[ ]*$/;

          //如果填写了,且不是空格,则ajax校验

          if(regnull.test(username.value) == false){

              msg.innerHTML = "";

             

              //xmlhttp赋值

              init();

             

              //准备发送的url

              var url = "CheckNameServlet?name=" + encodeURI(username.value) + "&r=" + Math.random();

              //打开发送通道(get表示get带参数,true表示是异步请求)

              xmlhttp.open("GET",url,true);

              //监测向后台发数据直到响应的整个过程

              xmlhttp.onreadystatechange = callBack;

              xmlhttp.send();//发送数据

          }else{

             msg.innerHTML = "请输入用户名";

          }

      }

     

      //状态发生改变时的回调函数

      function callBack(){

          //获取提示信息的span

          var msg = document.getElementById("msg");

         

          //获取状态 xmlhttp.status表示后台是否可访问的状态200表示可访问,404表示访问不到

          //alert(xmlhttp.readyState + " " +xmlhttp.status);

          if(xmlhttp.readyState == 4 && xmlhttp.status == 200){

              var r = xmlhttp.responseText;//获取响应文本

              //页面显示结果

              if(r == "used"){

                  msg.innerHTML = "该用户名已被占用,请尝试其他用户名";

              }else if(r == "useable"){

                  msg.innerHTML = "<span style='color:green'>用户名可用</span>";

              }else if(r == "noparam"){

                  msg.innerHTML = "参数错误,请刷新重试";

              }

          }else{

             msg.innerHTML = "检验中,请稍后……";

          }

      }

   </script>

 

CheckNameServlet

public class CheckNameServlet extends HttpServlet {

 

        

         public void doGet(HttpServletRequest request, HttpServletResponse response)

                            throws ServletException, IOException {

         this.doPost(request, response);              

         }

 

        

         public void doPost(HttpServletRequest request, HttpServletResponse response)

                            throws ServletException, IOException {

 

                   response.setContentType("text/html;charset=utf-8");

                   request.setCharacterEncoding("utf-8");

                   PrintWriter out = response.getWriter();

                  

                   //获取参数

                   String name = request.getParameter("name");

                   //对中文转码

                   if(name != null){

                            name = new String(name.getBytes("iso8859-1"),"utf-8");

                       System.out.println(name);

                            //如果是admin或者管理员表示占用,否则没有占用

                            if(name.equals("admin") || name.equals("管理员")){

                                     out.print("used");//千万不要写println否则会产生一个回车符,导致js判断出错

                            }else{

                                     out.print("useable");

                            }

                   }else{

                            out.print("noparam");

                   }

                  

                   out.flush();

                   out.close();

         }

 

}


Powered by 东方博宜教育咨询江苏有限公司  ©2008-2017 www.czos.cn