0
设置cookie将我使用Yii2
,我已经建立了登录过程的正常工作(饼干以及)通过标准的登录页面是不AJAX
。遇到问题通过AJAX登录与Yii2
我已经构建了一个下拉式登录字段,可以在登录时正常工作,但它似乎没有设置cookie,因为用户不会保持登录状态,并且没有创建任何bookie。
我想这是因为AJAX和cookie不是在用户系统上创建的,但在进一步阅读后,似乎应该工作。
我已验证cookie值设置是否正确,唯一的问题是cookie似乎未被创建。
我的登录代码:
JS:
function doLogin() {
// Set file to prepare our data
var loadUrl = "../../user/login/";
// Set parameters
var dataObject = $('#login_form').serialize();
// Set status element holder
var status_el = $('#login_status');
// Make sure status element is hidden
status_el.hide();
// Run request
getAjaxData(loadUrl, dataObject, 'POST', 'json')
.done(function(response) {
if (response.result == 'success') {
//.......
} else {
//.......
}
})
.fail(function() {
//.......
});
// End
}
function getAjaxData(loadUrl, dataObject, action, type) {
if ($('meta[name="csrf-token"]').length) {
// Add our CSRF token to our data object
dataObject._csrf = $('meta[name="csrf-token"]').attr('content');
}
return jQuery.ajax({
type: action,
url: loadUrl,
data: dataObject,
dataType: type
});
}
控制器:
public function actionLogin() {
// Check if they already logged in
if (!Yii::$app->user->isGuest and !Yii::$app->request->isAjax) {
return $this->redirect('/');
}
if (Yii::$app->request->isAjax) {
// Set our data holder
$response = ['output' => '', 'result' => 'error'];
}
// Let's send the POST data to the model and see if their login was valid
if (Yii::$app->request->isAjax and $this->user->validate() and $this->user->login()) {
$response['result'] = 'success';
} elseif (!Yii::$app->request->isAjax and Yii::$app->request->isPost and $this->user->validate() and $this->user->login()) {
//.......
} else {
//.......
}
if (Yii::$app->request->isAjax) {
echo Json::encode($response);
}
}
型号:
public function login() {
// Set cookie expire time
$cookie_expire = 3600 * 24 * Yii::$app->params['settings']['cookie_expire'];
return Yii::$app->user->login($this->getUser(), ($this->remember_me ? $cookie_expire : 0));
}
您是否为相同的域设置Cookie? – mmta41
@ mmta41是的,我让Yii处理它,并在通过标准过程成功设置cookie时将它设置为正确的域。 – Brett
只是一个快速的想法 - 它是否有帮助,如果你用'Yii :: $ app-> response-> format = \ yii \ web \ Response :: FORMAT_JSON替换最后一个'if'brackets的内容;返回$回应;' – Bizley