【问题标题】:How to load assets in Code Igniter such as JS files and CSS files如何在 Code Igniter 中加载资产,例如 JS 文件和 CSS 文件
【发布时间】:2026-02-04 09:25:01
【问题描述】:

给定文件结构并使用 WAMP

www
   application
       \views
           \templates
               header.php
   assets
       \js
          index.js
       \css
          index.css

我试图按照此解决方案中给出的示例Codeigniter: How to include javascript files 进行操作,但是我没有成功。

header.php

<html>
    <head>
            <?php $this->load->helper('url');?>
            <script type="text/javascript" src="<?php echo base_url();?>assets/js/index.js" ></script>
            <title>CodeIgniter Tutorial</title>

    </head>
    <body>


            <h1><?php echo $title ?></h1>

浏览器中抛出的错误是

GET http://localhost/index.php/localhost/assets/js/index.js 404 (Not Found)

header.php 正在被调用,因为它是我唯一一个带有 js 引用的 php 文件,抱歉,如果我误解了其他人的解决方案,我真的不明白为什么它不起作用

【问题讨论】:

  • 所以这就是你的基本 url http://localhost/index.php/localhost/ 这似乎不正确。
  • 尝试访问http://localhost/index.php/assets/js/index.js看看是否正常?
  • $config['base_url'] = 'localhost';刚刚尝试使用 src="assets/js/index.js"; 访问localhost/index.php/assets/js/index.js没有运气
  • 试试这个:&lt;script type="text/javascript" src="&lt;?php echo site_url(); ?&gt;assets/js/index.js"&gt;&lt;/script&gt;
  • 顺便说一句,您的配置文件中的站点 url 是什么?

标签: php codeigniter


【解决方案1】:

找到您的 httpd.conf 文件。

就我而言,它位于C:\wamp\bin\apache\apache2.4.9\conf

请取消注释LoadModule rewrite_module modules/mod_rewrite.so

在位于application\config\config.php 的config.php 中设置以下值。

$config['base_url'] = '';

回答我为什么取消注释mod_rewrite.sohere's the explaination的原因之一:

【讨论】:

  • 非常感谢,如果你不介意未来的裁判,你能解释一下你的溶胶吗
【解决方案2】:

constants.php下方config.php

打开constants.php,写一段这段代码方便你

define('ROUTE_STIE_PATH','`http://localhost/yoursitename/`');
define('ADMIN_CSS_DIR_FULL_PATH',ROUTE_STIE_PATH.'assets/css/');
define('ADMIN_JS_DIR_FULL_PATH',ROUTE_STIE_PATH.'assets/js/');

在标题上

<script src="<?php echo ADMIN_JS_DIR_FULL_PATH; ?>index.js" type="text/javascript"></script>

【讨论】:

  • 更改为 ;错误:GET localhost/index.php/localhost/index.phpassets/js/index.js 404(未找到)
  • 看看我的答案...在你的config.php .. $config['base_url'] = 'localhost/xxxxxx';最后,如果不放在那里,你必须在那里/签名
  • 我会尝试一下,现在@CharlesLiam 的回答很好
  • 我认为这是一个长期目标的好方法......如果它对你有用