jQuery 无刷新验证码是一种在不重新加载整个页面的情况下,实现验证码验证的技术。它通过 AJAX 技术与服务器进行通信,验证用户输入的验证码是否正确。
以下是一个简单的 jQuery 无刷新图片验证码示例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>jQuery 无刷新验证码</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<form id="captchaForm">
<img id="captchaImage" src="captcha.php" alt="验证码">
<input type="text" id="captchaInput" placeholder="请输入验证码">
<button type="submit">提交</button>
</form>
<script src="script.js"></script>
</body>
</html>
$(document).ready(function() {
$('#captchaForm').submit(function(event) {
event.preventDefault();
var userInput = $('#captchaInput').val();
$.ajax({
url: 'verify_captcha.php',
method: 'POST',
data: { captcha: userInput },
success: function(response) {
if (response === 'success') {
alert('验证码正确!');
} else {
alert('验证码错误,请重试!');
$('#captchaImage').attr('src', 'captcha.php?' + new Date().getTime());
$('#captchaInput').val('');
}
},
error: function() {
alert('请求失败,请重试!');
}
});
});
});
<?php
session_start();
// 生成验证码
$captcha = substr(md5(uniqid(mt_rand(), true)), 0, 6);
$_SESSION['captcha'] = $captcha;
// 创建图像
$image = imagecreatetruecolor(100, 30);
$bgColor = imagecolorallocate($image, 255, 255, 255);
$textColor = imagecolorallocate($image, 0, 0, 0);
imagefilledrectangle($image, 0, 0, 100, 30, $bgColor);
imagestring($image, 5, 20, 5, $captcha, $textColor);
header('Content-Type: image/png');
imagepng($image);
imagedestroy($image);
?>
<?php
session_start();
if (isset($_POST['captcha']) && $_POST['captcha'] === $_SESSION['captcha']) {
echo 'success';
} else {
echo 'fail';
}
?>
src
属性中添加时间戳,强制浏览器重新加载图片。src
属性中添加时间戳,强制浏览器重新加载图片。通过以上示例代码和解决方法,您可以实现一个基本的 jQuery 无刷新验证码功能,并解决常见的问题。
领取专属 10元无门槛券
手把手带您无忧上云