【Ajax】后台驗證用戶輸入的驗證碼是否與隨機生成的驗證碼一直


后台Java代碼【驗證碼生成】

  /**
     * 隨機生成6位隨機驗證碼
     */
    public static String createRandomVcode(){
        //驗證碼
        String vcode = "";
        for (int i = 0; i < 6; i++) {
            vcode = vcode + (int)(Math.random() * 9);
        }
        return vcode;
    }
    

后台Java代碼【使用驗證碼並將驗證碼保存到session里面】

 String authCode = xioo.createRandomVcode();        //隨機生成驗證碼

HttpSession session=request.getSession();             //session屬性
session.setAttribute("authCode", authCode);     // 保存驗證碼到session里面

后台Java代碼【將用戶輸入的驗證碼與session里面的驗證碼對比】

        HttpSession session=request.getSession();
        String usercode=request.getParameter("user_code");  //獲取用戶輸入的驗證碼
        String sessioncode=(String) session.getAttribute("authCode");  //獲取保存在session里面的驗證碼
        String result="";
        if( usercode != null && usercode.equals(sessioncode)){   //對比兩個code是否正確
            result = "1";
        }else{
            result = "0";
        }
        PrintWriter out = response.getWriter();
        out.write(result.toString());   //將數據傳到前台
    }

前台Ajax代碼【獲取用戶輸入的代碼傳到后台】

 $(document).ready(function() {
    $("#user_code").blur(function() {
        var user_code = $("#user_code").val();   //ur事件
        // 向后台發送處理數據  
        $.ajax({
            url : "CheckCode",    //目標地址
            data : "user_code=" + user_code,    //傳輸的數據
            type : "POST",      // 用POST方式傳輸 
            dataType : "text",    // 數據格式
            success : function(data) {
                data = parseInt(data, 10);
                if (data == 1) {
                    $("#error").html("<font color='#339933'>√ 短信驗證碼正確,請繼續</font>");
                } else if (data == 0){
                    $("#error").html("<font color='red'>× 驗證碼有誤,請核實后重新填寫</font>");
                }
            }
        });
    });
}); 
<input type="text" name="user_code" id="user_code" placeholder="請輸入驗證碼"/>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM