[英]CakePHP 2.0 Ajax login
我有以下方法允许用户登录到我的应用程序:
public function login()
{
if($this->Auth->user())
{
$this->Session->setFlash(__('Already logged in...'), 'default', array(), 'auth');
$this->redirect(array('controller'=>'pages','action'=>'display','home'));
}
if ($this->request->is('ajax'))
{
$this->layout = 'ajax';
if ($this->Auth->login())
{
}
else
{
}
}
else if ($this->request->is('post'))
{
if ($this->Auth->login())
{
return $this->redirect($this->Auth->redirect());
}
else
{
$this->Session->setFlash(__('Username or password is incorrect'), 'default', array(), 'auth');
}
}
}
它允许用户使用发布请求或ajax请求登录。 但是关于ajax请求,我如何使用JSON返回结果? 因此,例如,如果用户输入了错误的详细信息,则会传回错误消息?
我已经设置了jQuery AJAX,所以我只需要在成功方法中做一些额外的逻辑来处理返回,该逻辑要么显示来自服务器的错误消息,要么根据服务器的返回再次进行重定向。
例如
$('form').live('submit', function (event) {
// Declare the form
var form = $(this);
// Stop the form from doing a native postback
event.preventDefault();
// Get the data from the form
var data = form.serialize();
$.ajax({
type: form.attr('method'),
url: form.attr('action'),
data: data,
success: function (responseHtml) {
// If correct login details
if(success){
window.location.href('INSERT LOCATION TO REDIRECT TO FROM SERVER');
} else {
alert('INSERT MESSAGE FROM THE SERVER');
}
},
error: function (jqXHR, textStatus, errorThrown) {
alert('Error!');
}
});
});
有人可以帮忙吗? 我正在使用CakePHP 2.0,并且在网上和此处看到的所有教程都已经过时,或者对于我要实现的目标而言太过冗长。
编辑:您需要使用以下php代码
if ($this->Auth->login())
{
$arr = array("login" => "true" , "redirect" => "/redirect_url");
echo json_encode($arr);
}
else
{
$arr = array("login" => "false" , "error" => "Invalid Login Credentials");
echo json_encode($arr);
}
在javascript方面,您需要修改javascript以使用jQuery.getJSON处理json值。 此处提供jQuery.getJSON的示例http://api.jquery.com/jQuery.getJSON/
使用此jQuery代码
<script type="text/javascript">
$.getJSON("login.php", function(data) {
if(data.login)
{
//redirect user with data.redirect
}
else
{
//display error with data.error
}
})
</script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.