Ajax實現後台驗證用戶輸入的驗證碼是否與隨機生成的驗證碼一致。本站提示廣大學習愛好者:(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="請輸入驗證碼"/>
以上就是本文的全部內容,希望本文的內容對大家的學習或者工作能帶來一定的幫助,同時也希望多多支持!