在ThinkPHP5中進行頁面跳轉的兩種方法

thinkphp5中,跳轉地址是一個非常常見的需求。本文將介紹如何在thinkphp5中進行頁面跳轉。

在ThinkPHP5中,有兩種方式可以實現頁面跳轉。

方式一:使用跳轉助手函數

跳轉助手函數通過 redirect() 實現頁面跳轉。redirect() 函數接受一個參數,即跳轉地址。

1. 跳轉到控制器中的方法

public function index() {     // 跳轉到Index控制器中的hello方法     return redirect('index/hello'); }  public function hello() {     return 'Hello, ThinkPHP5!'; }

2. 跳轉到URL地址

public function index() {     // 跳轉到http://www.example.com/     return redirect('http://www.example.com/'); }

3. 帶參數跳轉

public function index() {     // 跳轉到Index控制器中的hello方法,并傳遞參數name     return redirect('index/hello', ['name' => 'ThinkPHP5']); }  public function hello($name) {     return 'Hello, ' . $name . '!'; }

方式二:使用控制器基類的 redirect 方法

ThinkPHP5中的控制器基類(Controller)中提供了 redirect() 方法來實現頁面跳轉。這種方式比使用跳轉助手函數更加靈活。

1. 跳轉到控制器中的方法

use thinkController;  class Index extends Controller {     public function index()     {         // 跳轉到Index控制器中的hello方法         return $this->redirect('hello');     }      public function hello()     {         return 'Hello, ThinkPHP5!';     } }

2. 跳轉到URL地址

use thinkController;  class Index extends Controller {     public function index()     {         // 跳轉到http://www.example.com/         return $this->redirect('http://www.example.com/');     } }

3. 帶參數跳轉

use thinkController;  class Index extends Controller {     public function index()     {         // 跳轉到Index控制器中的hello方法,并傳遞參數name         return $this->redirect('hello', ['name' => 'ThinkPHP5']);     }      public function hello($name)     {         return 'Hello, ' . $name . '!';     } }

? 版權聲明
THE END
喜歡就支持一下吧
點贊6 分享