您好,欢迎访问一九零五行业门户网

thinkphp跳转页封装教程

thinkphp是一个开源的php开发框架,它提供了强大的mvc模式支持,让开发者能够快速开发稳健的web应用。在开发web应用中,经常需要进行页面跳转,例如用户登录成功后需要跳转到用户界面。本文将介绍如何使用thinkphp进行页面跳转,并封装一个跳转页函数。
一、使用thinkphp进行页面跳转
thinkphp提供了两个内置函数可以进行页面跳转:
redirect()函数redirect()函数用于跳转到指定的url地址。它的语法如下:
redirect('url', '参数', '状态码')->send();
其中:
url:要跳转的url地址。参数:get方式的参数,可以是数组或者字符串。状态码:http状态码,例如302表示重定向,301表示永久重定向。例如,要跳转到http://www.example.com/user/index页面,代码如下:
redirect('http://www.example.com/user/index')->send();
success()和error()函数success()和error()函数用于在页面跳转时显示一个提示信息。成功提示信息使用success()函数,失败提示信息使用error()函数。它们的语法如下:
success('提示信息', '跳转url', '等待时间')->send();error('提示信息', '跳转url', '等待时间')->send();
其中:
提示信息:需要显示的信息,可以是字符串或数组。跳转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 = <<<eof <style type="text/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; } </style>eof; $html = <<<eof<!doctype html><html><head><meta charset="utf-8"><title>跳转提示</title>{$css}</head><body> <div class="jump"> <h3>跳转提示</h3> <p>{$message}</p> <p>等待时间:<span id="wait_time">{$waittime}</span>秒</p> <p><a href="{$url}">立即跳转</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></body></html>eof; echo $html;}
使用以上的封装函数可以在控制器中实现以下代码:
public function login() { if($this->request->post()){ $data = $this->request->post(); // 验证码验证 $user = usermodel::where('username', $data['username'])->find(); if(!$user || $user->password != $data['password']){ jump(url('login/index'), '用户名或密码错误', 3); } else { jump(url('user/index'), '登录成功', 3); } } return $this->fetch();}
以上就是使用thinkphp进行页面跳转并封装跳转页函数的教程。使用封装函数可以方便地在不同的控制器中重复使用。
以上就是thinkphp跳转页封装教程的详细内容。
其它类似信息

推荐信息