使用Ajax和验证的Zend表单

时间:2011-03-14 17:05:08

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

在“逻辑”问题之后,我有一个带有2个操作的控制器:

IndexAction:在视图内显示搜索表单脚本是Div标签,用于显示搜索结果。

该操作验证表单:

    public function indexAction()
    {
        $searchForm = new My_Form_Search();
        $statsService =  new My_Service_Statistics();

        if ($this->getRequest()->isPost()) {
            if ($searchForm->isValid($this->getRequest()->getParams())) {
                $this->_forward('ajax-do-search');
            } else {
                //???
                // i want to display the errors
                exit();
            }
        }

        $this->view->search = $searchForm;
    }

public function ajaxDoSearchAction()
{
    $this->view->result = array();
    $searchForm = new My_Form_Search();

    if ($this->getRequest()->isPost()) {
        if ($searchForm->isValid($this->getRequest()->getParams())) {
            $query = $searchForm->getValue('search');
            $search = new My_Service_Search();
            $hits = $search->find($query);
            // more...

        }
    }
}

如果有效则转发到“搜索”操作,并通过Jquery.form呈现视图 定义div。

但是,如果服务器端验证失败怎么办?没有“退出();”显示索引操作 在结果div里面。

我认为解决方案很简单,但今天的代码很多:-)

我知道我可以通过客户端验证来防止这种情况,但我推测php: -

1 个答案:

答案 0 :(得分:2)

你的设计不好IMO。

使用$ this-> _request-> isXmlHttpRequest()对您的代码进行分支。

然后回显整个页面(no-js fallback)或仅回显错误/结果

if ($this->_request->isXmlHttpRequest()) {
    if ($form->isValid($post)) {
        $result = array('status'=>'ok', 'data' => $model->getResults());
        $this->_json($result);
    } else {
        $result = array('status'=>'error', 'data' => $form->getErrors());
        $this->_json($result);
    }
} else {
    //like you would without ajax
}