【问题标题】:passing variable to default controller in codeigniter在codeigniter中将变量传递给默认控制器
【发布时间】:2013-03-30 13:06:12
【问题描述】:

我在 codeigniter 中有一个默认控制器

class Welcome extends CI_Controller {

    public function index()
    {
        $this->load->view('welcome_message');
    }

如你所知,我们可以调用这个函数

sitename/index.php

sitename/

因为我在 .htaccess 中有 url 重写

现在我想通过参数传递调用相同的索引函数

sitename/seo-services

seo-services 将参数传递给 index 函数以加载 seo-services 页面。

因为codeigniter的默认语法是

example.com/class/function/ID

我想要这种形式

example.com/class/ID

我想跳过类的默认(索引)函数的函数

我该怎么做?

谢谢

如您所见,我正在尝试这样做以达到 seo 的目的。

【问题讨论】:

    标签: php codeigniter


    【解决方案1】:

    附加到您的 url 的参数会自动转换为您的方法的参数。

    例如,如果您的欢迎控制器中有一个名为 index index 的方法,那么 http://www.example.com/index.php/welcome/index/[parametervalue] 会自动将 [parametervalue] 传递给您的方法,假设你定义你的函数来接收参数

    class Welcome extends CI_Controller {
    
        public function index($parameterValue=null)
        {
          //do whatever you need here
          //note the default value just in case it is null
        }
    }
    

    如果你想让事情变得更短,你必须在 config/routes.php 文件中定义一个别名。此外,如果您想摆脱 index.php,则必须相应地配置您的 Web 服务器(如果使用 apache,则通过 .htaccess 或如果使用 iis,则通过 web.config)

    【讨论】:

    • 亲爱的我做了同样的事,但我得到了错误 404 Page Not Found,实际上我正在尝试将值传递给默认控制器,我的 url 就像 localhost/seo-services
    • 如代码下方段落中所述。您首先需要设置 .htaccess (如这里的文档 ellislab.com/codeigniter/user-guide/general/urls.html 中所述)。然后,您需要修改 application/config/routes.php 中的路由(如此处ellislab.com/codeigniter/user-guide/general/routing.html 文档中所述)
    • 我想我无法解释你,看看默认语法是 example.com/class/function/ID 我想要 example.com/class/ID 我将跳过类的索引函数的函数
    • 非常感谢您的及时回复,您能给我举例路线吗?
    • 非常感谢您的及时回复,您能给我一个路线示例吗?实际上我有以下路线,但它不起作用 $route['(:any)'] = 'welcome/$1';
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-24
    • 1970-01-01
    相关资源
    最近更新 更多