2016-11-16 45 views
-1

我已經使用authcomponent在Cakephp中完成了簡單的登錄,它確實工作正常,我該如何使用ajax進行登錄?如何在CakePHP 2.8.0中進行AJAX登錄?

我有下面給出的是簡單的登錄使用代碼:

if ($this->request->is('post')) 
{ 
    if ($this->Auth->login()) 
    { 
     if ($this->Auth->user('role') === 'admin') 
     { 

      $this->redirect(array('admin' => false,'controller' => 'users','action' => 'index')); 

     } 
    } 
}   
+0

我猜你會需要一些JavaScript來發送憑據和JSON迴應說,無論是成功還是失敗。你可以用原始JavaScript來做到這一點,或者使用像jQuery這樣的庫。然後你可以使用一個控制器來給出正確的響應。 – halfer

+0

先生,我有使用$ .ajax jquery方法,但問題是,如何可以比較它 – Raju1990

+0

好吧,請添加您的JS代碼。我會假設你從JavaScript發送用戶名,密碼和角色。您可能需要使用其他控制器 - 使用上述PHP邏輯並根據需要返回帶有成功布爾值和錯誤字符串的JSON響應。 – halfer

回答

0

你的Ajax代碼應該是這樣的:

$(document).on('submit','#yourFormId',function(event){ 
    event.preventDefault(); 
    var data = $(this).serialize(); 
    var url = 'url_for_your_login_method'; /* like 'localhost/your_project_name/Users/login' */ 
    $.ajax({ 
    url:url, 
    type:'post', 
    data:data, 
    dataType:'json', 
    success:function(response) { 
     if(response == 1) { 
     // login success 
     } else { 
     // login fails 
     } 
    } 
    }); 
}); 

而在你的登錄方法應該是這樣的:

​​

對於Blowfish密碼哈希, 在您的AppController中:

<?php 
class AppController { 

    public $components = array(
    'Auth' => array(
     'authenticate' => array(
      'Form' => array(
       'passwordHasher' => 'Blowfish' 
      ) 
     ) 
     ) 
    ); 
    } 
    ?> 

而且在AppModel:

<?php 
    App::uses('BlowfishPasswordHasher', 'Controller/Component/Auth'); 


    class User extends AppModel { 

     public function beforeSave($options = array()) { 
     // if ID is not set, we're inserting a new user as opposed to updating 
      $passwordHasher = new BlowfishPasswordHasher(); 
      $this->data[$this->alias]['password'] = $passwordHasher->hash($this->data[$this->alias]['password']); 
     return true; 
    } 
} 
+0

你好HOw可以轉換密碼在河豚,因爲我們有使用ajax方法,所以cakephp不會自動轉換它河豚,請建議我.... – Raju1990

+0

請參閱編輯河豚散列答案.. –

+0

哈希不工作的情況下調用ajax – Raju1990