2016-11-16 46 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