我不太了解 codeigniter 中的路由概念,我想将许多参数传递给单个方法,如本 http://www.codeigniter.com/userguide2/general/controllers.html 中所述。教程页面。
在 url 我有这个
http://localhost/code_igniter/products/display/2/3/4
在我的 routes.php 中我写了
$route['products/display/(:any)'] = 'Products_controller/display';
我认为它会自动将所有参数(此处为 2/3/4)传递给“显示”方法,但我收到 404 页面未找到错误。
一般来说,我想实现类似的目标,如果 URI 是 controller/method
我想路由到 someother_controller/its_method
并将参数(如果有)传递给该方法.我该怎么做?
最佳答案
在 CI 3.x 中,(:any) 参数仅匹配单个 URI 段。例如:
$route['method/(:any)/(:any)'] = 'controller/method/$1/$2';
将恰好匹配两个段并适本地传递它们。如果你想匹配 1 或 2,你可以这样做(按顺序):
$route['method/(:any)/(:any)'] = 'controller/method/$1/$2';
$route['method/(:any)'] = 'controller/method/$1';
您可以像这样使用 (.+) 参数传递多个段:
$route['method/(.+)'] = 'controller/method/$1';
在这种情况下,$1 将包含 method/之后的所有内容。总的来说,我认为不鼓励使用它,因为你应该知道传递的是什么并适本地处理它,但有时 (.+) 会派上用场。例如,如果您不知道传递了多少参数,这将允许您捕获所有参数。还要记住,您可以像这样在方法中设置默认参数:
public function method($param=''){}
因此,如果没有传递任何内容,您仍然有一个有效值。
你也可以像这样传递给你的索引方法:
$route['method/(:any)/(:any)'] = 'controller/method/index/$1/$2';
$route['method/(:any)'] = 'controller/method/index/$1';
显然这些只是示例。您还可以包括文件夹和更复杂的路由,但这应该让您入门。
关于php - 如何将带有参数的 URI 路由到 codeigniter 中的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31691614/