2012-01-30 99 views
2

我使用Ajax提交表单。我在我的表单上使用了captcha,当我提交表单时没有任何验证错误,我第一次使用了captcha。有时服务器返回一些验证错误,并且不提交表单。此时我需要刷新验证码图像,而无需重新加载整个页面。如何重新加载表单通过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; 
}); 

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

感谢

回答

1

我没有在目前的例子,但我看着验证码是怎样的形式产生的,我想你可能需要做的就是回到了一个新的HTML代码是什么如果表单未通过验证,那么在您的json响应中使用captcha表单元素。

captcha元素使用对创建并存储在图像文件夹中的图像的引用,并且html使用与该图像关联的id。

如果您拨打$yourForm->getElement('captcha')->render();并将其添加到json响应中,则可以使用新的验证码元素更新您的页面。唯一的问题是使用默认装饰器调用渲染器可能会返回<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。

希望有所帮助。

+0

+1感谢您的回复。我正在看这个.. – Student 2012-01-31 19:26:13

相关问题