jquery验证码
jQuery 验证码实现方法
验证码(CAPTCHA)用于防止自动化脚本提交表单。jQuery 可以与后端结合实现验证码功能。
前端生成和验证
使用 jQuery 生成简单的验证码:
// 生成随机验证码
function generateCaptcha() {
let captcha = '';
const chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
for (let i = 0; i < 6; i++) {
captcha += chars.charAt(Math.floor(Math.random() * chars.length));
}
$('#captchaText').text(captcha);
return captcha;
}
// 初始化验证码
let currentCaptcha = generateCaptcha();
// 刷新验证码
$('#refreshCaptcha').click(function() {
currentCaptcha = generateCaptcha();
});
// 验证输入
$('#submitBtn').click(function() {
const userInput = $('#captchaInput').val();
if (userInput === currentCaptcha) {
alert('验证码正确');
} else {
alert('验证码错误');
currentCaptcha = generateCaptcha();
}
});
对应的 HTML 结构:

<div id="captchaText"></div>
<input type="text" id="captchaInput" placeholder="输入验证码">
<button id="refreshCaptcha">刷新验证码</button>
<button id="submitBtn">提交</button>
后端验证实现
对于更安全的验证码,通常需要后端生成和验证:
- 后端生成验证码(以 PHP 为例):
session_start();
$captcha = substr(md5(rand()), 0, 6);
$_SESSION['captcha'] = $captcha;
header('Content-type: image/png');
$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, 25, 8, $captcha, $textColor);
imagepng($image);
imagedestroy($image);
- 前端 jQuery 调用:
$('#captchaImage').attr('src', 'captcha.php?' + Math.random());
$('#refreshCaptcha').click(function() {
$('#captchaImage').attr('src', 'captcha.php?' + Math.random());
});
- 验证时发送到后端:
$.post('verify.php', { captcha: $('#captchaInput').val() }, function(response) {
if (response.valid) {
alert('验证成功');
} else {
alert('验证失败');
}
});
使用验证码插件
jQuery 有一些验证码插件可以简化实现:

-
jQuery Captcha 插件:
$('#form').captcha({ captchaUrl: 'captcha.php', verifyUrl: 'verify.php', errorMessage: '验证码错误' }); -
reCAPTCHA 集成:
<script src="https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit" async defer></script> <div id="recaptcha"></div> <script> function onloadCallback() { grecaptcha.render('recaptcha', { sitekey: 'YOUR_SITE_KEY' }); } </script>
安全性注意事项
- 避免纯前端验证,容易被绕过
- 验证码应存储在服务器会话中
- 限制验证码尝试次数
- 考虑使用第三方验证码服务如 reCAPTCHA
- 验证码应包含扭曲、噪声等防OCR特征
以上方法提供了从简单到复杂的 jQuery 验证码实现方案,可根据项目需求选择适合的方式。





