【问题标题】:Codeigniter routing causes function to be called multiple timesCodeigniter 路由导致函数被多次调用
【发布时间】:2013-05-05 06:21:08
【问题描述】:

我的类别控制器中有一个名为“插入”的函数。当我通过这样的 url 调用函数时:/categories/insert 它可以正常工作,但是如果我这样调用函数:/categories/insert/(最后是斜线),函数会被调用 3 次。

即使像这样调用我的编辑函数:/categories/edit/2 - 编辑函数也被调用了 3 次。

在 config/routes.php 我只有默认路由。我的 .htaccess 是这样的:

RewriteEngine on
RewriteCond $1 !^(index\.php|images|include|robots\.txt)
RewriteRule ^(.*)$ /index.php/$1 [L]  

编辑:

编辑功能代码:

public function edit($id = '') 
{
    $this->load->helper("form");
    $this->load->library("form_validation");
    $data["title"] = "Edit category";

    $this->form_validation->set_rules('category_name', 'Category name', 'required');

    if (!$this->form_validation->run())
    {
        $data['category'] = $this->categories_model->get_categories($id);
        $this->load->view("templates/admin_header", $data);
        $this->load->view("categories/edit", $data);
        $this->load->view("templates/admin_footer", $data); 
    }
    else
    {
        $this->categories_model->update($id);
        // other logic
    }
}

【问题讨论】:

  • 你怎么能说它叫了三遍呢?你能发布你的代码吗?
  • 我知道,因为我在代码的第一行有一个断点。我用函数的代码编辑了我的原始帖子。我不认为它与代码有任何关系,因为当我在 url 末尾调用不带斜杠的插入函数时,它可以正常工作。
  • 你的路线是什么样的?

标签: php codeigniter codeigniter-routing


【解决方案1】:

** 编辑 ** http://your.dot.com/insert 在没有 $arg 数据的情况下调用公共函数 insert($arg)。 http://your.dot.com/insert/ 使用 'index.php' 作为 $arg 调用插入。

routes.php

$route['edit/(:any)'] = 'edit/$1'

接受来自查询字符串的任何参数:yoursite.com/edit/paramyoursite.com/edit/2
它需要一个名为 edit 的方法。

如果您使用$route=['default_controller'] = 'foo' 作为所有方法的容器,请将路由更改为$route['edit/(:any)'] = 'foo/edit/$1' 或类似:$route['(:any)'] = 'foo/$1/$2' 作为路由的最后一行(注意:这适用于 yoursite.com/insert/paramyoursite.com/edit/param

foo.php

    public function insert() { ... }

    public function edit($id=null) { ... }

    /* End of file foo.php */


.htaccess

    RewriteCond $1 !^(index\.php)
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)$ /index.php?$1 [L]

【讨论】:

  • 如果我只调用一个视图,它会加载一次函数,就像应该的那样。但我需要那个模板,这是在官方 CI 教程中完成的方式。这是我的编辑功能。如果我在 url 的末尾没有斜杠,为什么我的插入函数被调用一次,而当我放一个斜杠时,我的插入函数被调用了 3 次?我的插入函数中也有三个视图。
  • 带有斜线,它可能正在寻找/index.php,或者该方法试图在斜线之后使用它期望的任何参数运行。见编辑。
  • 我刚刚浏览了我的网站的 base.php 控制器。我正在使用 HMVC 模式和模板,所以我不会像你一样加载视图。
  • 好的,谢谢。知道如何设置我的 .htaccess 或 routes.php,所以当我调用 /categories/edit/2 时,编辑函数不会被调用三次?我不想为每个控制器设置路由规则。我会的,但前提是这是唯一的解决方案。
  • 将我的设置添加到我的答案中。我没有特定于 .htaccess 文件中的路由或方法。
猜你喜欢
  • 1970-01-01
  • 2018-08-18
  • 2015-04-07
  • 2017-02-12
  • 2021-11-22
  • 2019-11-07
  • 1970-01-01
  • 2020-11-27
相关资源
最近更新 更多