我有一个使用codeigniter的验证码表单。我正在使用ajax重新加载验证码图像。但问题是,当我输入正确的代码时,它没有正常工作。它表明我给出的话是错误的。请帮忙
这是我的控制器:
function create_captcha(){
$this->load->helper('captcha');
$config = array('img_path' => './assets/captcha/',
'img_url' => base_url().'assets/captcha/',
'img_width' => '140',
'img_height' => '35',
'font_path' => './assets/fonts/OpenSans-ExtraBold.ttf',
'expiration' => 7200);
$captcha = create_captcha($config);
$image = $captcha['image'];
if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
echo $image;
}
else {
return $image;
}
$this->session->set_userdata('captchaword', $captcha['word']);
}
function check_captcha(){
$captcha_code = $this->input->post('captcha');
if ($captcha_code == $this->session->userdata('captchaword')) {
return TRUE;
}
else {
$this->form_validation->set_message('check_captcha', 'Wrong Captcha Code!');
return FALSE;
}
}
function seabooking()
{
$this->form_validation->set_rules('captcha', 'Captcha', 'trim|required|callback_check_captcha|xss_clean');
if ($this->form_validation->run() == FALSE) { //code} else { echo 'ok';}
}
以下是我的观点:
<label for="captcha" class="col-sm-3 control-label custom-label">Enter the Captcha</label>
<div class="col-sm-2 image" id="cap_div">
<?php echo $image;?>
</div>
<?php print_r($this->session->userdata('captchaword')); ?>
<a href="#" id="reload" class="clickedimage">Reload Image</a>
<div class="col-sm-4">
<input type="text" class="form-control" name="captcha" id="captcha" placeholder="Type captcha word" />
<?php echo form_error('captcha');?>
</div>
这是ajax调用代码:
<script type="text/javascript">
$(document).ready(function(){
$('.clickedimage').click(function(){
grabImage();
return false;
})
function grabImage()
{
$.ajax({
url: '<?php echo base_url('node/captcha_ajax');?>',
cache: false,
success: function(imagefromthecontroller) {
var newCaptcha = $('<div class="col-sm-2" id="cap_div">'+imagefromthecontroller+'</div>');
$('#cap_div').replaceWith(newCaptcha);
}
});
}
});
</script>
</body>
答案 0 :(得分:0)
当您重新加载验证码时,您并未保存验证码的新内容。
$this->session->set_userdata('captchaword', $captcha['word']);
上面这行代码需要在之前显示,然后返回$image
。
我还要查看以下代码:
(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest')
此条件似乎从this question获取并修改。正如您的问题中存在的那样,当$_SERVER['HTTP_X_REQUESTED_WITH']
不为空时,这种情况将始终为真,因为"xmlhttprequest"
将始终评估为真。