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 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据