在添加代码以验证匹配不起作用后,我有一个jQuery和php验证码
这是我的jQuery代码
$(document).ready(function() {
$('img#captcha-refresh').click(function() {
change_captcha();
});
function change_captcha(){
document.getElementById('captcha').src="reCaptcha/get_captcha.php?rnd=" + Math.random();
}
var captchascr = $('#captcha').attr('src');
$('#captcha-code').on('change', function(){
var captchaval = $(this).val();
if (captchascr == captchaval) {
console.log('match');
}else {
console.log('No match');
}
});
});
html
<div class="captcha-box">
<img src="reCaptcha/get_captcha.php" id="captcha" />
</div>
<div class="text-box">
<label>Type the two words:</label>
<input name="captcha-code" type="text" id="captcha-code">
</div>
<div class="captcha-action">
<img src="reCaptcha/refresh.jpg" id="captcha-refresh" />
</div>
这是php代码
session_start();
$word_1 = '';
for ($i = 0; $i < 4; $i++)
{
$word_1 .= chr(rand(97, 122));
}
for ($i = 0; $i < 4; $i++)
{
$word_2 .= chr(rand(97, 122));
}
$_SESSION['random_number'] = $word_1.' '.$word_2;
$dir = 'fonts/';
$image = imagecreatetruecolor(165, 50);
$font = "recaptchaFont.ttf"; // font style
$color = imagecolorallocate($image, 0, 0, 0);// color
$white = imagecolorallocate($image, 255, 255, 255); // background color white
imagefilledrectangle($image, 0,0, 709, 99, $white);
imagettftext ($image, 22, 0, 5, 30, $color, $dir.$font, $_SESSION['random_number']);
header("Content-type: image/png");
imagepng($image)
这里的会话是在php文件中创建的我只是不知道如何调用会话以便我进行匹配,有人可以帮忙吗?
答案 0 :(得分:1)
对AJAX
调用名为validate_captcha.php
的新文件。
PHP代码在文件中处理 AJAX调用
<?php
session_start();
$task = !empty($_POST['task']) ? $_POST['task'] : null;
$response = 'false';
if ( $task == 'validateCaptha' ){
$inputCaptcha = !empty($_POST['inputCaptcha']) ? $_POST['inputCaptcha'] : null;
$sessionCaptcha = $_SESSION['random_number'];
if ($inputCaptcha == $sessionCaptcha){
$response = 'true';
}else{
$response = 'false';
}
echo $response;
exit();
}
?>
jQuery AJAX代码
$(document).ready(function() {
$('img#captcha-refresh').click(function() {
change_captcha();
});
function change_captcha(){
document.getElementById('captcha').src="reCaptcha/get_captcha.php?rnd=" + Math.random();
}
$('#captcha-code').on('change', function(){
var inputCaptcha = $(this).val();
$.ajax({
url: 'reCaptcha/validate_captcha.php',
type: 'POST',
async: false,
data: {'task':'validateCaptha', 'inputCaptcha':inputCaptcha},
success: function(response){
if (response=='true'){
alert('Match');
}else{
alert('Not Match');
}
}
});
});
});
希望这可以帮助你。