我想使用 CakePHP 2.2 创建一个应用程序,允许非浏览器客户端连接和存储/访问数据。我一直在研究用户使用 UserController 中的这段代码登录的示例:
public function login()
{
if($this->request->is('post'))
{
if($this->Auth->login())
{
$this->Session->setFlash('Login Passed');
}
else
{
$this->Session->setFlash('Login Failed');
}
}
}
这是通过浏览器在浏览器上呈现一个表单,用户填写“用户名”和“密码”,然后单击按钮提交来完成的。我知道使用 Javascript 和 Ajax,您可以“序列化”表单并将其发送到服务器,但假设我不想(或不能)使用表单,只需让客户端发送两位信息:“用户名”和“密码”,我如何处理上面的“登录”方法中的这些数据?我知道 Auth->login
需要一个可选参数 $user
,但是有没有办法从用户名/密码组合中获取 $user
这样我就可以将其传递给Auth->login
?我想象这样的事情:
public function login()
{
if($this->request->is('post'))
{
if($this->Auth->login())
{
$this->Session->setFlash('Login Passed');
}
else
{
$this->Session->setFlash('Login Failed');
}
}
else if ($this->RequestHandler->isAjax())
{
$tmpUser = getUser ('username', 'password'); // ????? ===> Whatever call is needed here.
if($this->Auth->login($tmpUser))
{
$this->Session->setFlash('Login Passed');
}
else
{
$this->Session->setFlash('Login Failed');
}
}
}
最佳答案
您可以使用AuthComponent :: $ajaxLogin属性,同时通过 Ajax 登录实现 Auth。 除此之外,您可以尝试以下代码:
public function login()
{
if($this->request->is('post'))
{
if($this->Auth->login())
{
$this->Session->setFlash('Login Passed');
}
else
{
$this->Session->setFlash('Login Failed');
}
}
else if ($this->RequestHandler->isAjax())
{
$tmpUser['User']['username'] = $this->request->params['username'];
$tmpUser['User']['password'] = $this->request->params['password'];
if($this->Auth->login($tmpUser))
{
$this->Session->setFlash('Login Passed');
}
else
{
$this->Session->setFlash('Login Failed');
}
}
}
您可以使用 firebug 控制台检查响应。
关于ajax - CakePHP AuthComponent 使用 Ajax 登录而无需表单?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11512651/