Codeigniter路由导致函数被调用多次。

5

我的分类控制器中有一个名为“insert”的函数。当我通过网址调用该函数,如/categories/insert时,它可以正常工作,但是如果我像这样调用函数:/categories/insert/(末尾带斜杠),则该函数会被调用三次。

即使我像这样调用编辑功能:/categories/edit/2-编辑功能也会被调用三次。

在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
    }
}

你怎么说它被调用了三次?你能发一下你的代码吗? - Sudz
我知道,因为我在代码的第一行设置了断点。我在原始帖子中编辑了该函数的代码。我认为这与代码无关,因为当我在url末尾不加斜线调用插入函数时,它可以正常工作。 - Andrej
你的路由长什么样? - Dawson
1个回答

1

** 编辑 ** http://your.dot.com/insert 调用了公共函数 insert($arg),但没有为 $arg 提供数据。 http://your.dot.com/insert/ 将 'index.php' 作为 $arg 调用了 insert。

routes.php

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

接受来自查询字符串的任何参数:yoursite.com/edit/param或yoursite.com/edit/2。需要一个名为edit的方法。
如果你正在使用$route=['default_controller'] = 'foo'作为所有方法的容器,请将路由更改为$route['edit/(:any)'] = 'foo/edit/$1'或类似的$route['(:any)'] = 'foo/$1/$2'作为路由的最后一行(注意:这对于yoursite.com/insert/param和yoursite.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末尾没有斜杠时只被调用一次,而在加上斜杠时却被调用三次?我在插入功能中还有三个视图。 - Andrej
带有斜杠的话,它可能正在寻找/index.php,或者该方法正在尝试以斜杠后面期望的任何参数运行。请参见编辑。 - Dawson
我刚刚查看了我的站点的base.php控制器。我正在使用HMVC模式和模板,因此我不像你一样加载视图。 - Dawson
好的,谢谢。你有什么想法如何设置我的 .htaccess 或 routes.php,这样当我调用 /categories/edit/2 时,编辑功能不会被调用三次吗?我不想为每个控制器设置路由规则。如果那是唯一的解决方案,我会这样做。 - Andrej
将我的设置添加到答案中。我在 .htaccess 文件中没有特定于路由或方法的内容。 - Dawson

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接