我正在使用var name = $('#last').val();
并且我已经通过标准登录页面 not Yii2
设置了一个可以正常运行的登录过程(也是cookie)。
我已经建立了一个下拉登录字段,可以很好地登录它们,但它似乎没有设置cookie,因为用户没有保持登录状态并且没有创建过bookie。
我认为这是因为AJAX并且没有在用户系统上创建cookie,但是在进一步阅读时,它似乎应该工作。
我已经确认Cookie值正确设置,唯一的问题是Cookie似乎没有被创建。
我的登录代码:
JS:
AJAX
控制器:
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);
}
}
答案 0 :(得分:1)
正如我怀疑的那样(参见我之前的评论),如果只是回显数据,可能无法正确生成响应。或者Content-Type
标题很重要。如果有人能证实这一点,那就太好了。
无论如何,我很高兴它现在有用(数据需要returned
)。
您也可以使用Response
方便的format
。
public function actionLogin() {
// ...
if (Yii::$app->request->isAjax) {
Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
return $response;
}
}