0

我想在我的验证码图像旁边有一个重新加载按钮,以便在 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=" ">
4

3 回答 3

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);
           }
        });            
    });
});
于 2013-10-21T10:41:15.177 回答
2

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

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

#文件夹验证码权限为777或666的意思(读,写)

#然后看起来像 ci/captcha

#然后看起来像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;
    }
}
}

毕竟它运作良好!

于 2014-01-14T20:03:29.770 回答
-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> 
于 2013-10-21T11:37:53.427 回答