【问题标题】:Zend 1.12 + Ajax - Submit formZend 1.12 + Ajax - 提交表单
【发布时间】:2015-02-19 11:41:45
【问题描述】:

用户点击提交表单后,我需要调用 Zend 验证该表单而不刷新整个页面。我还在我的网站中使用 zend_Layout。我在这里看过很多教程,但仍然无法使其正常工作。

索引控制器:

class IndexController extends Zend_Controller_Action {

    public function init() {

    }

    public function indexAction() {
$this->view->static_data = "eg. ABCDEFG"; 

        $this->view->form = new Application_Form_Test();
    }
    public function ajaxAction() {
        // probably some code to hande ajax 
    }
}

查看索引/索引:

...
<?php 
echo date('m/d/Y h:i:s a', time());
echo $this->static_data; 
?>

<hr />
<?php echo $this->form ?>
...

表格:

class Application_Form_Test extends Zend_Form
{
    public function init()
    {
        $this->setMethod('post');
        $this->setAttrib('class', 'form1');

        $this->addElement('text', 'email', array(
            'label'      => 'Your email address:',
            'required'   => true,
            'filters'    => array('StringTrim'),
            'validators' => array(
                'EmailAddress',
            )
        ));

        $this->addElement('text', 'name', array(
            'label'      => 'Your name:',
            'required'   => true,
            'validators' => array(
                array('validator' => 'StringLength', 'options' => array(3, 20))
                )
        ));

        // Add the submit button
        $this->addElement('submit', 'submit', array(
            'ignore'   => true,
            'label'    => 'Send',
        ));

        // And finally add some CSRF protection
        $this->addElement('hash', 'csrf', array(
            'ignore' => true,
        ));
    }
}

那么我如何在不刷新该页面的其余部分的情况下验证表单并在该表单无效的情况下查看 Zend 错误消息。

【问题讨论】:

    标签: javascript jquery forms zend-framework twitter-bootstrap-3


    【解决方案1】:

    您可以将表单发布到您的 Ajax 操作中,您将在其中实例化表单并从请求中注入数据。

    $form = new Form();
    if ($this->getRequest()->isPost()) {
        if ($form->isValid($this->getRequest()->getPost())) {
            //save data
            ....
        }
    }
    $this->view->form = $form;
    

    你有两个选择:

    • 在视图中呈现表单并以 HTML 响应。使用 JavaScript 将当前表单替换为 Ajax 请求返回的 HTML。
    • 使用Zend_Form::getMessages() 获取错误消息并使用 JSON 响应。

      $this-view-&gt;messages = $form-&gt;getMessages();

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-09-16
    • 2015-09-06
    • 1970-01-01
    • 2011-06-17
    • 2014-02-19
    • 2011-05-09
    相关资源
    最近更新 更多