如何在点击刷新按钮上重新加载Zend Captcha图像?

Raj*_*hit 12 php captcha zend-framework

我在我的php页面中应用了一个zend验证码,现在我需要添加验证码重新加载按钮.请根据zend给出答案.

Ben*_*mer 17

只有两个快速的片段,但我想你会得到这个想法.根据需要调整元素名称和选择器.

在您的控制器中添加一个方法来生成新的验证码

public function refreshAction()
{
    $form = new Form_Contact();
    $captcha = $form->getElement('captcha')->getCaptcha();

    $data = array();

    $data['id']  = $captcha->generate();
    $data['src'] = $captcha->getImgUrl() .
                   $captcha->getId() .
                   $captcha->getSuffix();

   $this->_helper->json($data);
}
Run Code Online (Sandbox Code Playgroud)

在您的视图脚本中(我正在使用mootools来获取ajax请求)

document.addEvent('domready', function() {
     $$('#contactForm img').addEvent('click', function() {
        var jsonRequest = new Request.JSON({
            url: "<?= $this->url(array('controller' => 'contact', 'action' => 'refresh'), 'default', false) ?>",
            onSuccess: function(captcha) {
                $('captcha-id').set('value', captcha.id);
                $$('#contactForm img').set('src', captcha.src);
            }
        }).get();
    });
});
Run Code Online (Sandbox Code Playgroud)

编辑:添加了pahan的jquery

$(document).ready(function() {
    $('#refreshcaptcha').click(function() { 
        $.ajax({ 
            url: '/contact/refresh', 
            dataType:'json', 
            success: function(data) { 
                $('#contactForm img').attr('src', data.src); 
                $('#captcha-id').attr('value', data.id); 
            }
        }); 
    }); 
});
Run Code Online (Sandbox Code Playgroud)

  • 感谢代码,像魅力一样工作:)阅读本文后我用jquery做了.`$(document).ready(function(){$('#refreshcaptcha').click(function(){$ .ajax({url:'/ contact/refresh',dataType:'json',success:function( data){console.log(data)$('#contactForm img').attr('src',data.src); $('#captcha-id').attr('value',data.id); }});});});` (2认同)