【问题标题】:Passing parameters to index() in CodeIgniter在 CodeIgniter 中将参数传递给 index()
【发布时间】:2014-09-27 19:04:36
【问题描述】:

我的应用程序具有以下结构:

myapp/index.php: index page
myapp/mycont/myfunc/productID: dedicated page for product

index.php 的链接可以打开 myapp/mycont/myfunc/productID

因此,控制器功能定义为:

index() {...}
myfunc($id) {...}

因为,我的两个函数几乎相同,我想删除 myfunc() 函数并将 URL 更改为:

myapp/: index page
myapp/productID: dedicated page for product

以上两个网址都应该使用index()函数,但是如果我尝试向它传递参数,索引函数会抛出错误。

【问题讨论】:

    标签: php codeigniter url


    【解决方案1】:

    将参数传递给 CI 中的索引函数:

    1) 您需要 indexhttp://www.example.com/search/index/search-keyword
    2) 或者你需要使用路由$route['search/(:any)'] = 'search/index/$1';
    3) 或尝试remaphttps://ellislab.com/codeigniter/user-guide/general/controllers.html#remapping


    编辑(示例):

    $route['abc/campaigns/add_webengage_feedback_leads'] = "abc/campaigns/add_webengage_feedback_leads";
    $route['abc/campaigns/add_webengage_survey_leads'] = "abc/campaigns/add_webengage_survey_leads";
    $route['abc/campaigns/add_canvass_data'] = "abc/campaigns/add_canvass_data";
    $route['abc/campaigns/add_connecto_data'] = "abc/campaigns/add_connecto_data";
    $route['abc/campaigns/(:any)'] = "abc/campaigns/index/$1";
    

    注意:index函数的URL映射应该在最后。

    【讨论】:

    • 如果我使用这个 $route['search/(:any)'] = 'search/index/$1';它将影响搜索控制器中的所有方法。我该怎么做?
    • 确实如此。因此,您必须为该特定控制器定义路由中的所有 URL,注意映射到 index 函数的 URL 应该是最后一个。请检查编辑。
    • 没有任何替代选项。 Bcz 我在一个控制器中有太多方法。所以不可能路由每种方法。我认为这不是正确的方式。
    • 没有其他办法。实际上,在 Laravel、Django、RoR 等其他框架中,我们为 Views(即 CI 的 Controller)的每个方法定义了 URL
    【解决方案2】:

    假设您已从 URL 中删除了 index.php,您可以按照此流程进行操作,

    function index(){
        if( $this->uri->segment(3) ){     //if an product id is set
            $id = $this->uri->segment(3); //this is the product id in third segment of URL
        }else{                            //display the normal index page
    
        }
    }
    

    【讨论】:

    • 这行得通。不过,我想将类型的 URL:myapp/mycont/myfunc/productID 更改为 myapp/productID
    • 我使用了段(2)而不是段(3)。感谢这位兄弟
    猜你喜欢
    • 2018-02-06
    • 1970-01-01
    • 2011-08-19
    • 2011-06-16
    • 2023-04-05
    • 1970-01-01
    • 1970-01-01
    • 2018-01-20
    • 1970-01-01
    相关资源
    最近更新 更多