dsvs50005 2011-03-14 17:05
浏览 34
已采纳

使用Ajax和验证的Zend表单

Following "logical" Problem, i have an Controller with 2 Actions:

IndexAction: Display an Search Form, inside the view Script is an Div Tag to display search results.

The action validates the form:

    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...

        }
    }
}

If valid it forwards to the Search action, and the view is rendered via Jquery.form in the defined div.

But what to do if the server side validation failed? without "exit();" the index action is displayed inside the result div.

I think the solution is simple, but to much code today :-)

I know i can prevent this with client side validation, but i thrust php :-

  • 写回答

1条回答 默认 最新

  • doukang5966907 2011-03-14 18:46
    关注

    Your design is bad IMO.

    Branch your code using $this->_request->isXmlHttpRequest().

    Then echo either whole page (no-js fallback) or only the errors/results

    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
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 QT6颜色选择对话框显示不完整
  • ¥20 能提供一下思路或者代码吗
  • ¥15 用twincat控制!
  • ¥15 请问一下这个运行结果是怎么来的
  • ¥15 单通道放大电路的工作原理
  • ¥30 YOLO检测微调结果p为1
  • ¥15 DS18B20内部ADC模数转换器
  • ¥15 做个有关计算的小程序
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下