yii2中登录后跳转回登录前请求的页面

作者: php 发布时间: 2017-06-16 浏览: 4841 次 编辑

yii2中登录后跳转回登录前请求的页面,第一考虑的就是 goBack(),但是有时候会跳转的home页面

return $this->goBack();

出现这种情况,你可以用

 Yii::app()->request->referrer ; 

先看看Yii::$app->user->returnUrl是否已经设置,
returnUrl没有设置且goBack()中的参数也未设置则会返回到homeUrl指定的地址。

原因如下:

public yii\web\Response goBack ( $defaultUrl = null )
$defaultUrlstring|array

The default return URL in case it was not set previously. If this is null and the return URL was not set previously, yii\web\Application::homeUrl will be redirected to. Please refer to yii\web\User::setReturnUrl() on accepted format of the URL.

returnyii\web\Response

The current response object

可查阅官方文档中的这个地方,http://www.yiichina.com/doc/api/2.0/yii-web-contro...

好了现在我们就有了解决方法:就是在登录页面自己 setReturnUrl()

Yii::$app->user->setReturnUrl(Yii::$app->request->referrer);

其中Yii::$app->request->referrer 是获取上一个页面的url

直接上代码,大家自己体会吧:

public function actionLogin() {
    if (!Yii::$app->user->isGuest) {
        return $this->goHome();
    }
    $model = new LoginForm();
    if ($model->load(Yii::$app->request->post()) && $model->login()) {
        return $this->goBack();
    } else {
        //只需要添加这句话就可以了
        Yii::$app->user->setReturnUrl(Yii::$app->request->referrer);
        return $this->render('login', [
            'model' => $model,
        ]);
    }
}

好了,就这样解决了,不懂得,记得评论哦!