【问题标题】:Links, Controllers in CodeIgniterCodeIgniter 中的链接、控制器
【发布时间】:2013-12-16 22:29:40
【问题描述】:

我从 CI 开始,我需要一些帮助。我正在尝试使用 Ajax 加载一些 html 页面,这些 html 文件存储在视图文件夹中,并且我正在尝试使用控制器访问这些文件,但直到现在我还没有成功。我想知道如何访问这些文件,以及我使用的控制器是否正确或有更好的方法。

控制器

class Router extends CI_Controller
{
     public function index($file)
     {
           $this->load->view($file);
     }
}

Ajax

var SampleFunction = function (router) {//router is my base_url() + '/router'
    var pageContentBody = $('.page-content .page-content-body');

    if ($("#startLoadTag")){
        $.ajax({
            type: "post",
            cache: false,
            url: router + '/SampleLink.html',
            dataType: "html",
            success: function (html) {
                pageContentBody.html(html);
            }
        });
    }
}

直到现在我才得到 404 not found。

【问题讨论】:

  • 不确定您是否已将 apache 配置为删除索引,但如果没有,您应该点击 router+ '/index/SampleLink.html'
  • 无法在 codeigniter 中将参数传递给 function index()。将/ 视为方法路线。最简单的方法是创建另一个函数并在您的 ajax 路径中使用它
  • 好的,我修复了错误。但是现在我在系统上有一个很大的安全漏洞。如果我在 Chrome 上更改 HTML 链接名称并单击该链接,则会加载该文件。有任何东西可以阻止更改链接名称或增加安全性的东西。你有什么建议?

标签: php jquery ajax codeigniter


【解决方案1】:

这里的主要问题是只有当 URI 为 /router/ 时才会调用索引函数。最简单的解决方案是为您的方法命名不同:

class Router extends CI_Controller {
     public function details($file) {
           $this->load->view($file);
     }
}

SampleLink.html 的 URI 现在看起来像:/router/details/SampleLink.html。这非常简单,应该可以正常工作。此外,它不应干扰该控制器中的任何其他方法。

如果您真的不喜欢较长的 URL,那么您可以通过实现 _remap() 方法来缩短它。但如果您这样做,请记住您正在覆盖控制器的所有默认方法映射行为。

通过此实现,您可以使用 URI /router/SampleLink.html。但这就是你所能做的。控制器中没有其他方法可以访问。

class Router extends CI_Controller {
     public function _remap($file) {
           $this->load->view($file);
     }
}

最后,如果您想对文件使用自定义映射,但保留控制器通常的函数映射行为,您可以执行以下操作:

class Router extends CI_Controller {

     public function _remap($method, $args=array()) {

           $callable = array($this, $method);

           if ($method[0] != '_' && is_callable($callable))
               // If $callable really is a usable method in this class, then
               // go ahead and invoke it with the given $args array.  Make sure
               // to exclude method names starting with '_', which are supposed to
               // be kept private and inaccessible from the web.
               call_user_func_array($callable, $args);
           else  
               // Otherwise, look for a view with the name $method.  Hopefully,
               // this will be something like "SampleLink.html", which exists in
               // the views folder.
               $this->load->view($method); 
     }

}

【讨论】:

    猜你喜欢
    • 2020-04-10
    • 2015-11-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多