我刚开始使用CodeIgniter,在使用基于分段的url时遇到了一些问题。我知道如何称呼他们做$variable = $this->uri->segment(2);
,但每当我转到url时,我都会得到404。对于URI路由,我需要做些什么吗?
例如,我试图转到localhost/ci/index.php/games/1000(其中1000是游戏ID),但我得到了404。localhost/ci/index.php/games/运行良好。
为了实现这一点,您需要一个名为games.php
的控制器,该控制器具有以下内容
class Games extends CI_Controller
{
public function index($id)
{
echo $id;
}
}
除非你做这样的
class Games extends CI_Controller
{
public function index()
{
echo 'this is index';
}
public function game($id)
{
echo $id;
}
}
并将其添加到您的routes.php
中
$route['game/(:any)'] = "games/game/$1";
默认情况下,URI的第二段是控制器中CI自动调用的方法(函数)。
因此,在您的情况下,您实际上试图在游戏控制器中调用一个名为1000()
的函数,但该函数不存在,因此会导致404。
相反,我认为您要做的是调用index()
函数,并将变量1000
传递给它
因此,如果你要转到localhost/ci/index.php/games/index/1000
,你就不应该再得到404了,但是你的URI段现在得到变量1000
是错误的。
以下是一个具有更正的URI段的控制器的工作示例:
class Games extends CI_Controller
{
// good habit to call __construct in order to load
// any models, libraries, or helpers used throughout this controller
public function __construct()
{
parent::__construct();
}
// default controller
public function index()
{
// this should display 1000
echo $this->uri->segment(3);
}
}