Ajax verifies that the verification code entered by the user is consistent with the randomly generated one
- 2020-06-12 09:14:34
- OfStack
Background Java code [Captcha generation]
/**
* Randomly generated 6 Bit random verification code
*/
public static String createRandomVcode(){
// Verification code
String vcode = "";
for (int i = 0; i < 6; i++) {
vcode = vcode + (int)(Math.random() * 9);
}
return vcode;
}
Background Java code [Use captchAs and save them in session]
String authCode = xioo.createRandomVcode(); // Generate captcha randomly
HttpSession session=request.getSession(); //session attribute
session.setAttribute("authCode", authCode); // Save the captcha to session inside
Background Java code [Compare the verification code entered by the user with the verification code in session]
HttpSession session=request.getSession();
String usercode=request.getParameter("user_code"); // Gets the verification code entered by the user
String sessioncode=(String) session.getAttribute("authCode"); // Get saved in session The captcha inside
String result="";
if( usercode != null && usercode.equals(sessioncode)){ // Compare the two code Whether it is right
result = "1";
}else{
result = "0";
}
PrintWriter out = response.getWriter();
out.write(result.toString()); // Send the data to the front desk
}
Foreground Ajax code [To obtain user input code and send it to the background]
$(document).ready(function() {
$("#user_code").blur(function() {
var user_code = $("#user_code").val(); //ur The event
// Sends processing data to the background
$.ajax({
url : "CheckCode", // The target address
data : "user_code=" + user_code, // Transmitted data
type : "POST", // with POST Way to transport
dataType : "text", // The data format
success : function(data) {
data = parseInt(data, 10);
if (data == 1) {
$("#error").html("<font color='#339933'> Square root The SMS verification code is correct, please continue </font>");
} else if (data == 0){
$("#error").html("<font color='red'> x Verification code is wrong, please fill in again after verification </font>");
}
}
});
});
});
<input type="text" name="user_code" id="user_code" placeholder="请输入验证码"/>