我刚刚开始使用CodeIgniter,我在使用基于段的网址时遇到了一些问题。我理解如何调用它们$variable = $this->uri->segment(2);
,但每当我访问网址时,我都会收到404.我是否需要为URI路由做些什么?
例如,我试图转到localhost / ci / index.php / games / 1000(其中1000将是游戏ID),但我得到的是404. localhost / ci / index.php / games /工作正常。
答案 0 :(得分:3)
为了使其工作,您需要一个名为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";
答案 1 :(得分:2)
默认情况下,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);
}
}