【Ajax】後台驗證使用者輸入的驗證碼是否與隨機產生的驗證碼一直,ajax驗證碼

來源:互聯網
上載者:User

【Ajax】後台驗證使用者輸入的驗證碼是否與隨機產生的驗證碼一直,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="請輸入驗證碼"/>

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.