使用jquery和codeigniter重新加载验证码图像

时间:2013-10-21 10:34:44

标签: jquery codeigniter captcha

我想在我的验证码图像旁边有一个重新加载按钮,用codeigniter中的jquery重新加载它。我在网上搜索找到了解决方案,但我发现的一切都让我很困惑。

这是我的控制者:

function create_captcha()
{                                
    $expiration = time()-300; // Two hour limit
    $this->db->query("DELETE FROM captcha WHERE captcha_time < ".$expiration);
    $vals = array(
                //'word'         => 'Random word',
                'word_length' => 4,
                'img_path' => './uploads/captcha/',
                'img_url' => base_url().'uploads/captcha/',
                'font_path' => './system/fonts/texb.ttf',
                'img_width' => '110',
                'img_height' => '30',
                'expiration' => '3600'
            );

    $cap = create_captcha($vals);

    //puts in the db
    $captchadata = array(
                'captcha_id'    => '',
                'captcha_time'  => $cap['time'],
                'ip_address'    => $this->input->ip_address(),
                'word'          => $cap['word']
            );

    $query = $this->db->insert_string('captcha', $captchadata);
    $this->db->query($query);

    if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') echo $cap['image'];
    else return $cap['image'];

这是我的观点:

<div class="captcha-area">
    <? echo form_input('captcha', '', 'class="field text captcha"')?>
    <div id="cap-img">
        <? echo $image;?>
    </div>
    <a title="reload" class="reload-captcha" href="#"><img src="<? echo base_url(); ?>images/reload.png" /></a>                                
    <div class="clear"></div>
 </div>
 <script>
      $(function(){
          var base_url = '<?php echo base_url(); ?>';
          $('.reload-captcha').click(function(event){
              event.preventDefault();
              $('.captcha-img').attr('src', base_url+'dashboard/create_captcha?'+Math.random());
          });
       });
 </script>

修改

这是加载网站后的源代码

<div class="captcha-area">
   <input type="text" name="captcha" value="" class="field text captcha">
   <div id="cap-img">
       <img src="http://example.com/uploads/captcha/1382346264.1026.jpg" width="110" height="30" class="captcha-img" style="border:0;" alt=" ">
   </div>
   <a title="reload" class="reload-captcha" href="#"><img src="http://example.com/images/reload.png"></a>                                
   <div class="clear"></div>
</div>

当我点击重新加载按钮时,它会将src属性更改为:

<img src="http://example.com/dashboard/create_captcha?0.8049291325733066" width="110" height="30" class="captcha-img" style="border:0;" alt=" ">

3 个答案:

答案 0 :(得分:2)

附加您的controller name并使用ajax之类的,

$(function(){
    var base_url = '<?php echo base_url(); ?>';
    $('.reload-captcha').click(function(event){
        event.preventDefault();
        $.ajax({
           url:base_url+'dashboard/create_captcha?'+Math.random(),
           success:function(data){
              $('.captcha-img').attr('src', data);
           }
        });            
    });
});

答案 1 :(得分:2)

  

#您可以使用ajax重新加载img并使用javascript查看我的代码

     

#您必须在CI根文件夹中创建文件夹验证码

     

#777或666的文件夹验证码权限(读取,写入所有)

     

#Then看起来像ci / captcha

     

#Then看起来像ci / application

     

我的html.php视图

<html>
<head>
<script>
    function postRequest(strURL) 
    {
        var xmlHttp;
        if (window.XMLHttpRequest) // Mozilla, Safari, ...
        { 
            var xmlHttp = new XMLHttpRequest();
        } 
        else if (window.ActiveXObject) // IE 
        { 
             var xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
        else
        {
            alert("your browser does not support AJAX");
            return;
        }
        xmlHttp.open('POST', strURL, true);

        xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

        xmlHttp.onreadystatechange = function() 
        {

            if (xmlHttp.readyState == 4 && xmlHttp.status==200) 
            {
                reload_captcha(xmlHttp.responseText);
            }
        }
        xmlHttp.send(strURL);
    }

    function reload_captcha(str)
    {
        document.getElementById("captcha-img").innerHTML = str;
    }

    function get_captcha()
    {
        //<a href="#" onclick="JavaScript:get_captcha()" ></a>
        document.getElementById("captcha-img").innerHTML = '<img src="<?php echo base_url('asset/img/loader.gif'); ?>" height="35" width="37" />';
        var url="<?php echo base_url('index/reload_captcha'); ?>";
        postRequest(url);
    }
</script>
</head>
<body>
<label>Human test</label>
<input type="text" autocomplete="off" maxlength="5" name="captcha" value="" />
<span id="captcha-img" class="captcha-img">
    <?php echo $captcha_img; ?>
</span>
<a href="#reload" onclick="JavaScript:get_captcha()" ><img class="reload-img" src="<?php echo base_url('asset/img/reload.png'); ?>" alt="reload" /></a>
</body>
</html>
  

我的index.php控制器

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Index extends CI_Controller
{
    public function __construct()
    {
        parent::__construct();
        $this->load->database();
        $this->load->library('form_validation');
        $this->load->helper('date');
    }
    public function index()
    {
        $this->form_validation->set_rules('captcha', 'Security','trim|required|xss_clean|callback_check_captcha');

        if($this->form_validation->run() == False)
        {
            $data['captcha_img'] = $this->get_captcha();

        $this->load->view('html',$data);
    }
}

private function _generate_string($min, $max)
{
    $pool = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
    $pool = str_shuffle($pool);
    $str = '';

    for ($i = 0; $i < 5; $i++)
    {
        $str .= substr($pool, mt_rand(0, strlen($pool) -1), 1);
    }

    return $str;
}

public function get_captcha()
{
    $this->load->helper('captcha');

    $word = $this->_generate_string(2,5);

    $vals = array(
                    'word' => $word,
        'img_path'   => './captcha/',
        'img_url'    => base_url().'captcha/',
        'img_width'  => 120,
        'img_height' => 35,
        'border' => 0, 
        'font_path' => './system/fonts/texb.ttf',
        'expiration' => 3600 //1 houre
    );

    $cap = create_captcha($vals);

    $this->session->set_userdata($cap['word']);

    return $cap['image'];
}

public function reload_captcha()
{
    $new_captcha = $this->get_captcha();
    echo "".$new_captcha;
}

public function check_cap_tcha()
{
    $session_captcha_code = $this->session->userdata('word');

    if($session_captcha_code == $user_captcha_code)
    {
        return true;
    }else{
        $this->form_validation->set_message('check_captcha', "Security code does not match !");
        return false;
    }
}
}
  

毕竟它运作良好!

答案 2 :(得分:-1)

我改变了Ruhan Kumar的代码,可以获得令人满意的代码:

<script>
     $(function(){
         var base_url = '<?php echo base_url(); ?>';
         $('.reload-captcha').click(function(event){
             event.preventDefault();
             $.ajax({
                 url:base_url+'admin/dashboard/create_captcha',
                 success:function(data){
                     $('.captcha-img').replaceWith(data);
                 }
             });            
          });
      });
</script>