你的 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
}
}
});
});
在你的登录方法中应该是这样的:
if ($this->request->is('post'))
{
if ($this->Auth->login())
{
if ($this->Auth->user('role') === 'admin')
{
$output = 1; // login success and role is admin
} else {
$output = 0; // login success but role is not admin
}
} else {
$output = 2; // login fails
}
$this->set(array(
'output'=>$output,
'_serialize'=>'output'
));
}
对于 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;
}
}