• Ajax实现验证码异步校验


    验证码异步校验可以防止表单提交后因验证码不正确导致已填的其它项都清空。

    整个过程图如下

    验证码输入框出代码

     1 <div class="form-group">
     2     <label for="date" class="col-sm-2 control-label">验证码</label>
     3     <div class="col-sm-3">
     4         <input type="text" class="form-control" name="checkCode" id="checkCode" onblur="checkCodeFn()">
     5     </div>
     6     <div class="col-sm-2">
     7     <img src="${pageContext.request.contextPath }/checkImg" onclick="changeImg(this)" />
     8     </div>
     9     <div id="checkCodeDiv">
    10                         
    11     </div>16 </div>

    ajax异步校验代码

     1 <script type="text/javascript">
     2 
     3     function checkCodeFn() {
     4         //alert(666);
     5         var checkCode_client = $("#checkCode").val();
     6         $.ajax({
     7             "async":true,
     8             "url":"${pageContext.request.contextPath}/checkCode",
     9             "data":{"checkCode_client":checkCode_client},
    10             "type":"POST",
    11             "dataType":"json",
    12             "success":function(data) {
    13                 $("#checkCodeDiv").html(data.info);
    14                 $("#checkCodeDiv").css("color","red");
    15             }  
    16     
    17         });
    18     }
    19 </script>

    进行验证码校验的servlet

     1 package com.alphajuns.web.servlet;
     2 
     3 import java.io.IOException;
     4 import javax.servlet.ServletException;
     5 import javax.servlet.http.HttpServlet;
     6 import javax.servlet.http.HttpServletRequest;
     7 import javax.servlet.http.HttpServletResponse;
     8 
     9 public class CheckCodeServlet extends HttpServlet {
    10 
    11     public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    12         request.setCharacterEncoding("utf-8");
    13         // 获得用户输入的验证码
    14         String checkcode_client = request.getParameter("checkCode_client");
    15         // 获得图片中生成的验证码
    16         String checkcode_session = (String) request.getSession().getAttribute("checkcode_session");
    17         // 比较生成的验证码和输入的验证码
    18         if (!checkcode_client.equals(checkcode_session)) {
    19             response.getWriter().write("{"info":"incorrect"}");
    20         } else {
    21             response.getWriter().write("{"info":""}");
    22         }
    23     }
    24 
    25     public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    26         doGet(request, response);
    27     }
    28 }

    测试结果可行

  • 相关阅读:
    python dataframe根据变量类型选取变量
    史上最简单的Xgboost安装教程 for Python3.7 on Win10!亲测有效!
    Python三种基础数据类型:列表list,元祖tuple和字典dict
    Time 模块
    第二周 3(实战:中国大学排名定向爬虫)
    第二周 2(信息标记与提取)
    第二周 1(beautiful soup库)
    第一周 2(requests库实战)
    第一周 1 (requests库)
    pd.concat()
  • 原文地址:https://www.cnblogs.com/alphajuns/p/10041651.html
Copyright © 2020-2023  润新知