跳转和重定向

namespace appindexcontroller;

use thinkController;
use appindexmodelUser;

class Index extends Controller
{
    public function index()
    {
        $User = new User; //实例化User对象
        $result = $User->save($data); 
        if($result){
            //设置成功后跳转页面的地址,默认的返回页面是$_SERVER['HTTP_REFERER']
            $this->success('新增成功', 'User/list');
        } else {
            //错误页面的默认跳转页面是返回前一页,通常不需要设置
            $this->error('新增失败');
        }
    }
}

重定向

hinkController类的redirect方法可以实现页面的重定向功能。

redirect方法的参数用法和Url::build方法的用法一致(参考URL生成部分),例如:

//重定向到News模块的Category操作
$this->redirect('News/category', ['cate_id' => 2]);

上面的用法是跳转到News模块的category操作,重定向后会改变当前的URL地址。

或者直接重定向到一个指定的外部URL地址,例如:

//重定向到指定的URL地址 并且使用302
$this->redirect('http://thinkphp.cn/blog/2',302);

可以在重定向的时候通过session闪存数据传值,例如

$this->redirect('News/category', ['cate_id' => 2], 302, ['data' => 'hello']);

使用redirect助手函数还可以实现更多的功能,例如可以记住当前的URL后跳转

redirect('News/category')->remember();

需要跳转到上次记住的URL的时候使用:

redirect()->restore();
原文地址:https://www.cnblogs.com/mmore123/p/12848309.html