如何在CakePHP2.8.0中进行AJAX登录?
我已经使用authcomponent在Cakephp中完成了简单的登录,它确实工作得很好,我如何使用ajax进行登录 我有以下简单登录的使用代码:如何在CakePHP2.8.0中进行AJAX登录?,ajax,cakephp,cakephp-2.8,Ajax,Cakephp,Cakephp 2.8,我已经使用authcomponent在Cakephp中完成了简单的登录,它确实工作得很好,我如何使用ajax进行登录 我有以下简单登录的使用代码: if ($this->request->is('post')) { if ($this->Auth->login()) { if ($this->Auth->user('role') === 'admin') { $this->r
if ($this->request->is('post'))
{
if ($this->Auth->login())
{
if ($this->Auth->user('role') === 'admin')
{
$this->redirect(array('admin' => false,'controller' => 'users','action' => 'index'));
}
}
}
您的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'
));
}
对于河豚密码哈希,
在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;
}
}
我想您需要一些JavaScript来发送凭证,并需要一个JSON响应来说明它是否成功。您可以使用原始JavaScript或使用jQuery之类的库来实现这一点。然后,您可以使用控制器给出正确的响应。先生,我使用了$.ajaxjquery方法,但问题是如何比较itOK,请添加您的JS代码。我假设您正在从JavaScript发送用户名、密码和角色。您可能需要另一个控制器来实现这一点-使用上面的PHP逻辑,并根据需要返回一个带有成功布尔值和错误字符串的JSON响应。先生,我想说的是,如何比较$this->Auth->login()方法中通过ajax发送的值。我的密码也是以哈希格式存储的,它使用blowfish进行哈希,所以我使用这个方法转换blowfish中的密码$hash=Security::hash($this->request->data['User']['password'],'blowfish',$savepass);但每次密码的散列方式都不一样,请帮忙我不知道,因为我不使用CakePHP。我在手册中做了一个快速搜索,-您可以根据用户名和密码组合搜索用户。您好,如何在blowfish中转换密码,因为我们使用ajax方法,所以cakephp不会自动将其转换为blowfish,请建议我…检查控制台中的ajax响应。我使用过这个,但如果($this->request->is('ajax'){$this->layout='ajax';$this->autoRender=false;如果($this->Auth->login()){echo'yes';或者{echo'no';}}您的请求类型是post,因此请检查($this->request->is('post'))。