duanbozhong9689 2016-10-01 13:56
浏览 115
已采纳

使用Yii2通过AJAX登录设置cookie时遇到问题

I'm using Yii2 and I have setup a login process which works fine (cookies as well) via the standard login page which is not AJAX.

I have built a dropdown login field which works fine at logging them in, however it doesn't seem to set the cookie as the user doesn't stay logged in and there is no bookie created.

I figured that this was because of AJAX and the cookie wasn't being created on the users system, but upon further reading it seems it should work.

I have verified that the cookie value is being set correctly, the only issue is the cookie doesn't seem to being created.

My login code:

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
    });

}

Controller:

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);
    }

}

Model:

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));

}
  • 写回答

1条回答 默认 最新

  • dongxin5429 2016-10-05 16:12
    关注

    As I suspected (see my earlier comment) response might not be correctly generated in case of simply echoing the data. Or maybe Content-Type header matters. If someone can confirm this it will be great.

    Anyway, I'm glad it works now (data needs to be returned).

    And you can use Response handy format as well.

    public function actionLogin() {
    
        // ...
    
        if (Yii::$app->request->isAjax) {
            Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
    
            return $response;
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 有偿求qftp工具。能连接,下载文件,发送代码,windows环境,最好qt6 要qt creator写的
  • ¥70 刚刚看到一个人的网站居然是通过cname访问的
  • ¥15 Attributeerror:super object has no attribute '__sklearn_tags__'_'
  • ¥15 逆置单链表输出不完整
  • ¥15 宇视vms-B200-A16@R启动不了,如下图所示,在软件工具搜不到,如何解决?(操作系统-linux)
  • ¥500 寻找一名电子工程师完成pcb主板设计(拒绝AI生成式答案)
  • ¥15 关于#mysql#的问题:UNION ALL(相关搜索:sql语句)
  • ¥15 matlab二位可视化能否针对不同数值范围分开分级?
  • ¥15 已经创建了模拟器但是不能用来运行app 怎么办😭自己搞两天了
  • ¥15 关于#极限编程#的问题,请各位专家解答!