2011-09-02 134 views
1

我使用Auth組件。我有一個Ajax登錄表單,我希望在沒有頁面刷新的情況下在表單下顯示成功/失敗消息。CakePHP:以Ajax登錄表單顯示失敗/成功消息

但是,當我提交表單(使用jquery.form.js):

$('#loginform').ajaxForm(function(data) { 
    alert(data); 
}); 

它返回警報home.ctp內容在成功的情況下和在失敗的情況下返回的登錄表單的HTML代碼!

我想在alert(data)中收到$this->Auth->loginError

這些都是一些app_controller beforeFilter設置:

function beforeFilter(){ 
    $this->Auth->loginRedirect = false; 
    $this->Auth->logoutRedirect = false; 
    $this->Auth->loginError = __('Invalid e-mail or password.', true); 
    $this->Auth->autoRedirect = false; 
    $this->autoRender = false; 
    $this->render('login','ajax'); 
} 

我用loginRedirect呈現一些邏輯,使一個JSON對象jQuery的過程。

回答

3

您可以使用博客帖的解決方案CakePHP Form Validation with Ajax Using jQuery

基本上,問題是,從一個的Ajax請求經由區分標準

if ($this->RequestHandler->isAjax()) { /*If it is an Ajax call*/ } 
else { /* If it is a standard action request */ } 

,仍然需要把調試級別爲0(Configure::write('debug',0)),並使用Ajax的佈局不輸出標準XHTML佈局中的數據/app/views/layouts/default.ctp

調試提交的表單的是這樣的:

Configure::write('debug', 0); 
    $this->layout = 'ajax'; 
    if ($this->RequestHandler->isAjax()) { 
     if (!empty($this->data)) { 
      $this->Post->create(); 
      $this->Post->set($this->data['Post']); 
      if($this->Post->validates()) { 
       if ($this->Post->save($this->data)) { 
        $message = __('The Post has been saved.', true); 
        $data = $this->data; 
        $this->set('success', compact('message', 'data')); 
       } 
      } else { 
       $message = __('The Post could not be saved. Please, try again.', true); 
       $Post = $this->Post->invalidFields(); 
       $data = compact('Post'); 
       $this->set('errors', compact('message', 'data')); 
      } 
     } 
    } 

而且它以JSON格式作出後的輸出:

// Error output 
{"errors":{ 
    "message":"The Post could not be saved. Please, try again.", 
    "data":{ 
     "Post":{ 
      "title":"This field cannot be left blank.", 
      "body":"This field cannot be left blank." 
     } 
    } 
}} 

// Success output 
{"success":{ 
    "message":"The Post has been saved.", 
    "data":{ 
     "Post":{ 
      "id":"", 
      "title":"Lorem ipsum dolor sit amet", 
      "body":"Lorem ipsum dolor sit amet, aliquet ...", 
      "published":"1" 
     } 
    } 
}}