【问题标题】:How to reload captcha on form submit via Ajax?如何在通过 Ajax 提交的表单上重新加载验证码?
【发布时间】:2012-01-30 19:43:52
【问题描述】:

我正在使用 Ajax 提交表单。我在我的表单上使用验证码,当我提交表单时它第一次运行完美,没有任何验证错误。有时服务器会返回一些验证错误并且不提交表单。此时我需要刷新验证码图像而不重新加载整个页面。

Zend 形式的验证码:

$captcha= new Zend_Form_Element_Captcha('captcha', array(
                'id'=>'captcha',
                'title'=>'Security Check.',
                'captcha'  => array(
                'captcha'  => 'Image',
                'required' => true,
                'font'     => '../public/fonts/ARIALN.TTF',
                'wordlen'  => '6',
                'width'    => '200',
                'height'   => '50',
                'imgdir'   => '../public/images/captcha/',
                'imgurl'   => '/images/captcha/'
                )));

用于表单提交的jQuery:

jQuery('form.AjaxForm').submit( function() {

    $.ajax({
        url     : $(this).attr('action'),
        type    : $(this).attr('method'),
        dataType: 'json',
        data    : $(this).serialize(),
        success : function( data ) {
                      // reload captcha here
                      alert('Success'); 
                  },
        error   : function( xhr, err ) {
                      // reload captcha here
                      alert('Error');
                }
    });

    return false;
}); 

如何在表单提交时重新加载验证码?

谢谢

【问题讨论】:

    标签: php jquery zend-framework zend-form captcha


    【解决方案1】:

    我目前没有示例,但我查看了表单中的验证码是如何生成的,我认为您可能需要做的是为您的 json 中的验证码表单元素返回一个新的 html 代码如果表单验证失败,则响应。

    验证码元素使用对图像的引用,该图像被创建并存储在图像文件夹中,而 html 表单使用与该图像关联的 id。

    如果您调用 $yourForm->getElement('captcha')->render(); 并将其添加到 json 响应中,您可以使用新的验证码元素更新您的页面。唯一的问题是使用默认装饰器调用 render 可能会返回 <dt><dd> 标签,并且您将不得不在 html 中用 javascript 替换它。如果您使用的是自定义装饰器,那么它对您来说可能会有所不同,或者您可以只渲染图像和隐藏字段而不是标签并将其插入到 div 标签中。

    // in your controller where the form was validated
    $form = new Form();
    if (form->isValid($this->getRequest()->getPost()) == false) {
        $captcha = $form->getElement('captcha')->render();
        $json['captchahtml'] = $captcha;
    }
    
    $this->view->json = json_encode($json);
    

    然后在您的 jquery success 回调中,检查表单是否未通过验证并更新验证码 html。

    希望对您有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-08-06
      • 1970-01-01
      • 1970-01-01
      • 2019-01-20
      • 2011-11-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多