【问题标题】:Yii CGridView catch Ajax Response and solve session timeoutYii CGridView 捕获 Ajax 响应并解决会话超时
【发布时间】:2014-03-04 09:59:16
【问题描述】:

我正在使用Yii MVC

用户已登录;

我正在使用带有 2 个标签的浏览器;

从第二个选项卡,我注销了用户,所以,现在,用户也从第一个选项卡登录;

现在,我尝试在 gridview 中使用 ajax call 查询 db

用户已注销,所以,我得到一个302 状态码;

这是我要捕获此错误的地方,并将用户重定向到登录页面,因为会话已过期;

在内部,Yii 尝试将我重定向到 login 页面,但失败了;

我看到带有200 状态代码的login 操作,但没有重定向;

我找到了一些关于此行为的信息,但它不起作用:

Using loginRequiredAjaxResponse to solve ajax session timeout

我尝试使用一个新鲜的yii项目,因为我怀疑user module是罪魁祸首;

不是用户模块,是yii;

在框架中,在CAccessControlFilter中,调用了如下函数;

如果会话已过期并且我刷新页面,我可以看到死亡消息;

但如果会话已过期并且我有一个 ajax 调用,则不会发生重定向;

protected function accessDenied($user,$message)
    {
        die(__FUNCTION__);
        debug_print_backtrace();
        if($user->getIsGuest())
            $user->loginRequired();
        else
            throw new CHttpException(403,$message);
    }

main.php文件的组件->用户下,我设置了'loginRequiredAjaxResponse' => 'YII_LOGIN_REQUIRED',

【问题讨论】:

  • 请分享一些代码。

标签: php jquery ajax session yii


【解决方案1】:

http://www.yiiframework.com/wiki/321/using-loginrequiredajaxresponse-to-solve-ajax-session-timeout/

在模板或视图中输入此代码:

<?php
        /*
         * if ajax call and session has expired, then redirect to user/login
         */
        if (Yii::app()->components['user']->loginRequiredAjaxResponse) {
            Yii::app()->clientScript->registerScript('ajaxLoginRequired', '
            jQuery("body").ajaxComplete(
                function(event, request, options) {
                    if (request.responseText == "' . Yii::app()->components['user']->loginRequiredAjaxResponse . '") {
                        window.location.href = "'.Yii::app()->createUrl('/user/login').'";
                    }
                }
            );
        ');
        }
        ?>

在自定义成员控制器中,将其放入 init 方法中

    if (Yii::app()->user->isGuest) {
        /*
         *  covers even the ajax requests if user session has expired
         */
        Yii::app()->user->loginRequired();
    }

【讨论】:

    猜你喜欢
    • 2011-04-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-20
    • 1970-01-01
    • 1970-01-01
    • 2011-04-28
    相关资源
    最近更新 更多