23

这似乎很基本,但我无法掌握它。

我正在尝试向控制器中的方法发送多个参数,如下所示:

http://localhost/ci/index.php/subjects/3/state

这是我尝试过的路由:

$route['subjects/(:num)'] = 'subjects/view/$1';
$route['subjects/(:num)/{:any}'] = 'subjects/view/$1/$2';

该方法接受2个参数:

public function view($slug, $id = null){

}

但我似乎得到了 404。我怎样才能让它工作?我需要视图方法始终接受 1 个参数和可选的其他参数。

注意:我包括 url 助手。

4

3 回答 3

44

您的路由括号有问题只需将其从 {} 更改为 () 括号即可

$route['subjects/(:num)/{:any}'] = 'subjects/view/$1/$2';

$route['subjects/(:num)/(:any)'] = 'subjects/view/$1/$2';
于 2012-11-06T07:41:41.780 回答
10

始终维护您的路由规则

$route['subjects/(:num)/(:any)/(:any)/(:any)'] = 'subjects/view/$1/$2/$3/$4';
$route['subjects/(:num)/(:any)/(:any)'] = 'subjects/view/$1/$2/$3';
$route['subjects/(:num)/(:any)'] = 'subjects/view/$1/$2';

始终遵循此模式进行路由

如果你像这样添加

$route['subjects/(:num)/(:any)'] = 'subjects/view/$1/$2';
$route['subjects/(:num)/(:any)/(:any)/(:any)'] = 'subjects/view/$1/$2/$3/$4';
$route['subjects/(:num)/(:any)/(:any)'] = 'subjects/view/$1/$2/$3';

那么总是第一个条件每次都为真。

另请参阅此链接--> codeigniter 路由规则

于 2014-10-15T12:16:19.827 回答
3

我曾经尝试过这个 URI 模式

$route['(:any)'] = 'welcome/list1/$1';
$route['(:any)/(:num)'] = 'welcome/list1/$1/$2';

$route['(:any)/(:any)'] = 'welcome/list2/$1/$2';
$route['(:any)/(:any)/(:num)'] = 'welcome/list2/$1/$2/$3';

$route['(:any)/(:any)/(:any)'] = 'welcome/list3/$1/$2/$3';

但它没有用......所以我用正则表达式替换它

([a-z 0-9 -]+)更换(:any)([0-9]+)更换(:num)

所以它变成了

$route['([a-z 0-9 -]+)'] = 'welcome/list1/$1';
$route['([a-z 0-9 -]+)/([0-9]+)'] = 'welcome/list1/$1/$2';

$route['([a-z 0-9 -]+)/([a-z 0-9 -]+)'] = 'welcome/list2/$1/$2';
$route['([a-z 0-9 -]+)/([a-z 0-9 -]+)/([0-9]+)'] = 'welcome/list2/$1/$2/$3';

$route['([a-z 0-9 -]+)/([a-z 0-9 -]+)/([a-z 0-9 -]+)'] = 'welcome/list3/$1/$2/$3';

它对我有用:)

于 2016-02-20T11:20:25.997 回答