zoukankan      html  css  js  c++  java
  • thinkphp5 三种重定向(跳转)

    页面跳转

    在应用开发中,经常会遇到一些带有提示信息的跳转页面,例如操作成功或者操作错误页面,并且自动跳转到另外一个目标页面。系统的 hinkController类内置了两个跳转方法successerror,用于页面跳转提示。

    使用方法很简单,举例如下:

    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('新增失败');
            }
        }
    }
    

    跳转地址是可选的,success方法的默认跳转地址是$_SERVER["HTTP_REFERER"],error方法的默认跳转地址是javascript:history.back(-1);

    默认的等待时间都是3秒

    successerror方法都可以对应的模板,默认的设置是两个方法对应的模板都是:

    THINK_PATH . 'tpl/dispatch_jump.tpl'
    

    我们可以改变默认的模板:

    //默认错误跳转对应的模板文件
    'dispatch_error_tmpl' => APP_PATH . 'tpl/dispatch_jump.tpl',
    //默认成功跳转对应的模板文件
    'dispatch_success_tmpl' => APP_PATH . 'tpl/dispatch_jump.tpl',
    

    也可以使用项目内部的模板文件

    //默认错误跳转对应的模板文件
    'dispatch_error_tmpl' => 'public/error',
    //默认成功跳转对应的模板文件
    'dispatch_success_tmpl' => 'public/success',
    

    模板文件可以使用模板标签,并且可以使用下面的模板变量:

    变量含义
    $data 要返回的数据
    $msg 页面提示信息
    $code 返回的code
    $wait 跳转等待时间 单位为秒
    $url 跳转页面地址

    error方法会自动判断当前请求是否属于Ajax请求,如果属于Ajax请求则会自动转换为default_ajax_return配置的格式返回信息。 success在Ajax请求下不返回信息,需要开发者自行处理。

    重定向

    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();
  • 相关阅读:
    中国历史朝代公元对照简表
    [Solved] DashBoard – Excel Service: The data sources may be unreachable, may not be responding, or may have denied you access.
    Delete/Remove Project from TFS 2010
    Sharepoint site showing system account instead of my username on the top right corner.
    你的成功在于你每天养成的习惯
    Internet Information Services is running in 32bit emulation mode. Correct the issue listed above and rerun setup.
    Prepare to back up and restore a farm (Office SharePoint Server 2007)
    Word中字号与磅值的对应关系
    How to: Change the Frequency for Refreshing the Data Warehouse for Team System
    UI Automation in WPF/Silverlight
  • 原文地址:https://www.cnblogs.com/ifyoukonw/p/7089899.html
Copyright © 2011-2022 走看看