yii2中登錄後跳轉回登錄前請求的頁面,第一考慮的就是 goBack(),但是有時候會跳轉的home頁面
return $this->goBack();
出現這種情況,你可以用
Yii::app()->request->referrer ;
先看看Yii::$app->user->returnUrl是否已經設置,
returnUrl沒有設置且goBack()中的參數也未設置則會返回到homeUrl指定的地址。
原因如下:
public yii\web\Response goBack ( $defaultUrl = null ) | ||
$defaultUrl | string|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. |
return | yii\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, ]); } }
好了,就這樣解決了,不懂得,記得評論哦!