ajax - CakePHP AuthComponent 使用 Ajax 登录而无需表单?

标签 ajax json cakephp authentication

我想使用 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/

相关文章:

javascript - 在 Sails 中访问 JSON 请求参数

php - 在 Cakephp 中将两个模型之间的表链接在一起

ajax - Angularjs 多ajax请求优化

ajax - 使用 jsdom 加载 ajax 应用程序

javascript - 如何保护页面免受高科技 CRSF 的影响

ios - 如何在 UI TextView 中显示 YouTube 搜索 API 响应?

objective-c - 我在我的应用程序中使用 NSJSONSerialization,这个应用程序可以在 IOS 3.x 下正常运行吗?

php - CakePHP 1.3 - where 子句中的未知列

php - Croogo - 管理菜单在实时服务器上显示错误

python - 使用 Bottle 的 AJAX 提交表单(Python)