CakePHP Ajax登录系统

时间:2011-11-20 20:56:53

标签: php ajax cakephp

我正在尝试创建一个ajax登录脚本但是已经碰壁了。我以前建了一个,但现在使用cakephp framwework。 我不太确定要去做这件事。目前我在控制器中有一个登录功能,

public function login()
{
    if($this->request->is('post')) {
        if($this->Auth->login()) {
            $this->Session->setFlash('Login Passed');
        } else {
            $this->Session->setFlash('Login Failed');
        }
    }
}

然后我使用ajax从表单发送值吗?这些行来自我的旧(非cakephp)系统,

xmlhttp.open("POST","http://www.site.com/login/",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("AttemptLogin=true&AccountEmail="+ userMail +"&AccountPassword=" + userPass);

我应该以任何方式修改它们吗?另外,我如何使用errorsetc处理任何验证和登录尝试。

很抱歉这个问题很开放,很长但我不知道去哪里,我找了教程但却找不到。

非常感谢 克里斯

1 个答案:

答案 0 :(得分:1)

您可以使用cake中的javascript helper并使用一个转换模板 对json格式的响应,在控制器中只包含帮助程序:

var $helpers = array('Javascript');
var $components = array('RequestHandler');

//the template ie "/views/templates/ajax.ctp"
echo $javascript->object(isset($response) ? $response : array());

所以你可以设置你的功能:

public function login()
{
  if($this->RequestHandler->isPost()) {
     if($this->Auth->login()) {
        $response('success'=>true);
     } else {
        $response('success'=>false);
     }
   $this->set('response', $response);
   $this->render(null, 'ajax');
}

javascript我推荐jQuery

$.ajax({url:"/controller/login",type:"POST", data:$('#formLogin').serialize(), dataType:"json", success:responseLogin, context:this});

 function responseLogin(response)
 {
     //here is the object returned by cakephp
     if(!response.success)
        //do something the user don't login
     else
       //do something the user pass the login
 }