2011-03-14 72 views
1

繼「邏輯」的問題,我有2個操作的控制器:使用Ajax Zend的形式和驗證

的indexAction:顯示一個搜索表,裏面的視圖Script是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... 

     } 
    } 
} 

如果有效將其轉發給搜索行動,並認爲在 定義DIV通過Jquery.form呈現。

但如果服務器端驗證失敗怎麼辦?沒有「exit();」索引操作在結果div中顯示爲 。

我認爲解決的辦法很簡單,但很多代碼今天:-)

我知道我可以防止這種與客戶端驗證,但我推力PHP: -

回答

2

你的設計是壞IMO。

使用$ this - > _ request-> isXmlHttpRequest()來分支代碼。

然後附和或者整個頁面(無JS回退)或僅錯誤/結果

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 
} 
+0

你是對的,但現在我必須使用JSON打印結果( - : – opHASnoNAME 2011-03-15 16:16:56

+1

沒有你不必須;)你可以執行'$ this-> render('my-ajax-viewscript');'以及。這只是我的最佳實踐;) – 2011-03-15 17:59:07

+0

嗨,剛剛更改了代碼昨天完全到您的評論:-)現在我看到的事情更清晰!非常感謝! – opHASnoNAME 2011-03-16 06:21:04