【问题标题】:Code Igniter controller - can't use uri->segment with function index()?Code Igniter 控制器 - 不能将 uri->segment 与函数 index() 一起使用?
【发布时间】:2010-03-29 22:11:40
【问题描述】:

我正在使用代码点火器,由于某种原因,url http://mysite.com/account/100 给了我一个 404 错误,但 http://mysite.com/account 实际上有效。这是我的控制器 account.php 的样子。

   class account extends Controller {


    function account()
    {
      parent::Controller();
    }

    function index()
    {
     echo 'hello';
      echo $this->uri->segment(2);
    }
    }

知道有什么问题吗?

【问题讨论】:

  • 可能是它试图将 100 作为方法而不是参数调用,所以尝试 account/index/100 看看它是否改变。
  • 啊,你是对的。是否可以将 100 不视为函数?例如,如果没有找到函数,则将其视为 url 变量?
  • 似乎没有,至少在不编辑 CodeIgniter 的情况下不会。
  • 我收回这一点,例如,您可以使用路由来做到这一点。 $route['account/(:num)'] = "account/index/$1" 我相信这会起作用。有关详细信息,请参阅 URI 路由用户指南。 codeigniter.com/user_guide/general/routing.html
  • 非常感谢,您能否在您的答案中添加该路由提示,然后我会检查标记它

标签: codeigniter controller


【解决方案1】:

我刚刚测试了一个像你一样的简单帐户类,它试图调用 100 作为帐户方法,而不是你在 index.php 之后的 URL 应该是 account/index/100 并且它工作正常。

这可以通过例如路由来解决。

$route['account/(:num)'] = "accounts/index/$1";

是您正在寻找的。您可以查看URI Routing 用户指南 了解更多信息。

CodeIgniter 要求您的控制器名称大写,文件名小写,因此请尝试将您的控制器更改为。

class Account extends Controller { }

还有你的文件名 account.php

【讨论】:

  • 抱歉,这只是我的问题中的输入错误。我实际上在我的控制器中加入了括号,它被命名为 account.php
【解决方案2】:

添加这条路线,你就很好了

$route['account/(:any)'] = "account/index/$1";

【讨论】:

    【解决方案3】:

    这不起作用,因为当您请求 http://example.com/account 时,它看起来像 index() 方法。 但是当你请求http://example.com/account/100 时,正在寻找100() 方法。哪个不存在。 您可以像这样调整代码。

    class account extends Controller {
     public function account()
     {
       parent::Controller();
     }
    
     public function index()
     {
      echo 'hello';
     }
    
     public function id(){
      echo $this->uri->segment(2);
     }
     public function alternative($id){
      echo $id;
     }
    }
    

    你会这样调用 url:http://example.com/account/id/100

    或者你可以这样做 http://example.com/account/alternative/100

    【讨论】:

      猜你喜欢
      • 2010-10-30
      • 2014-06-03
      • 1970-01-01
      • 1970-01-01
      • 2016-08-15
      • 1970-01-01
      • 1970-01-01
      • 2011-03-03
      • 2016-05-19
      相关资源
      最近更新 更多