thinkphp跳转页封装教程

thinkphp是一个开源的php开发框架,它提供了强大的mvc模式支持,让开发者能够快速开发稳健的web应用。在开发web应用中,经常需要进行页面跳转,例如用户登录成功后需要跳转到用户界面。本文将介绍如何使用thinkphp进行页面跳转,并封装一个跳转页函数。

一、使用ThinkPHP进行页面跳转

ThinkPHP提供了两个内置函数可以进行页面跳转:

  1. redirect()函数

redirect()函数用于跳转到指定的URL地址。它的语法如下:

redirect('url', '参数', '状态码')->send();

其中:

立即学习PHP免费学习笔记(深入)”;

  • url:要跳转的URL地址。
  • 参数:GET方式的参数,可以是数组或者字符串
  • 状态码:http状态码,例如302表示重定向,301表示永久重定向。

例如,要跳转到http://www.example.com/user/index页面,代码如下:

redirect('http://www.example.com/user/index')->send();
  1. success()和Error()函数

success()和error()函数用于在页面跳转时显示一个提示信息。成功提示信息使用success()函数,失败提示信息使用error()函数。它们的语法如下:

success('提示信息', '跳转URL', '等待时间')->send(); error('提示信息', '跳转URL', '等待时间')->send();

其中:

立即学习PHP免费学习笔记(深入)”;

  • 提示信息:需要显示的信息,可以是字符串或数组。
  • 跳转URL:要跳转的URL地址,可以省略。
  • 等待时间:等待时间,单位为秒,默认为1秒,可以省略。

例如,要显示一个成功提示信息并跳转到http://www.example.com/user/index页面,代码如下:

success('登录成功', 'http://www.example.com/user/index')->send();

二、封装跳转页函数

为了方便重复使用,我们可以将页面跳转进行封装。下面是一个简单的跳转页函数代码:

/**  * 跳转页函数  *  * @param string $url 要跳转的URL地址  * @param string $message 信息提示  * @param int $waitTime 等待时间  * @return void  */ function jump($url, $message = '', $waitTime = 1) {     if (empty($url)) {         exit('错误:未指定跳转URL地址!');     }     if (!empty($message)) {         $message = htmlspecialchars($message);     }     if ($waitTime == 0) {         header("Location: {$url}");         exit;     }     $css =      .jump {         text-align:center;         padding-top:5%;         font-family: 'Microsoft Yahei', Verdana, Arial;         font-size:16px;     }     .jump h3 {         font-size:24px;         font-weight:bold;     }      EOF;     $html =    <meta charset="UTF-8"><title>跳转提示</title> {$css}       <div class="jump">         <h3>跳转提示</h3>         <p>{$message}</p>         <p>等待时间:<span id="wait_time">{$waitTime}</span>秒</p>         <p><a href="%7B%24url%7D">立即跳转</a></p>     </div>     <script type="text/javascript">         var wait_time = {$waitTime};         var interval = setInterval(function(){             if(wait_time > 0) {                 wait_time--;                 document.getElementById('wait_time').innerHTML = wait_time;             } else {                 clearInterval(interval);                 window.location.href = '{$url}';             }         }, 1000);     </script> EOF;     echo $html; }

使用以上的封装函数可以在控制器中实现以下代码:

public function login() {     if($this-&gt;request-&gt;post()){         $data = $this-&gt;request-&gt;post();         // 验证码验证          $user = UserModel::where('username', $data['username'])-&gt;find();         if(!$user || $user-&gt;password != $data['password']){             jump(url('login/index'), '用户名或密码错误', 3);         } else {             jump(url('user/index'), '登录成功', 3);         }     }     return $this-&gt;fetch(); }

© 版权声明
THE END
喜欢就支持一下吧
点赞6 分享