【问题标题】:Passing parameters in CodeIgniter在 CodeIgniter 中传递参数
【发布时间】:2013-10-26 21:30:14
【问题描述】:

我一直在努力解决这个问题大约一个小时。我看起来高高在低,但没有什么对我有用。这应该很简单,我敢肯定。

我正在尝试将 CodeIgniter 中的一些参数传递给 URL,但似乎没有任何效果。这是我的控制器:

class Form_controller extends CI_Controller {
    public function change($key = NULL) {
        if (is_null($key)) {
            redirect("reset");
        } else {
            echo "Hello world!";
        }
    }
}

这是我的路线:

$route['change/(:any)'] = "form_controller/change/$1";

每次我访问/index.php/change/hello 时,我都会收到字符串“Hello world!”但是当我访问 /index.php/change 时,我发现 404 未找到。

我想要做的是将一个参数传递给我的控制器,以便检查数据库中的特定键,然后对其进行操作。如果数据库中不存在密钥,那么我需要将它们重定向到其他地方。

对此有什么想法吗?

【问题讨论】:

标签: php codeigniter


【解决方案1】:

没关系,我想通了。我最终制定了两条不同的路线来处理它们,如下所示:

$route['change'] = "form_controller/change";
$route['change/(:any)'] = "form_controller/change/$1";

控制器中的函数现在看起来像这样:

public function change($key = NULL) {
    if (is_null($key)) {
        redirect("reset");
    } else if ($this->form_model->checkKey($key)) {
        $this->load->view("templates/gateway_header");
        $this->load->view("forms/change");
        $this->load->view("templates/gateway_footer");
    } else {
         redirect("reset");           
    }
}

如果有人有更好的解决方案,我会全力以赴。不过这对我有用。

【讨论】:

    【解决方案2】:

    这可能对你有帮助

    public function change() {
     $key = $this->uri->segment(3);
    

    http://ellislab.com/codeigniter/user-guide/helpers/url_helper.html

    这使您可以使用 CI url 帮助程序轻松抓取细分

    index.php/change/(3RD Segment) 这部分将进入那个变量$key。

    这可能不是您想要的,但如果您尝试传递两个或更多变量,它会非常有用,因为您可以从 url 中获取段并将其存储到变量中

    【讨论】:

      猜你喜欢
      • 2016-12-07
      • 2014-09-27
      • 1970-01-01
      • 1970-01-01
      • 2021-09-06
      • 1970-01-01
      • 2021-05-15
      • 1970-01-01
      • 2011-08-19
      相关资源
      最近更新 更多