1. 程式人生 > >Ajax實現驗證碼非同步校驗

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 }

測試結果可行