简体   繁体   中英

Codeigniter - Include javascript that is inside the application/libraries folder (script tag)

I can't come up with a solution to the following problem. Let's say i have a library (.php) file that I put inside codeigniter's library folder but that library has some javascript associated with it: I have the library "grid.php" and it has "grid.js" that comes with it. And when I load the library "grid" the

<script src="base_url(). 'application/libraries/grid/grid.js'></script>

is echoed in the page where I have used the grid. The problem is that the ".js" file gets forbidden access and therefore cannot be used. I dont want to put my grid in the root level of codeigniter because I won't be able to load it with $this->load->library('grid') and I dont want move my js files manually to the root and then include them manually every time I use the grid I just want to copy and paste the grid folder to every project I need and when I use it it would include the js link automatically. Help me please :)

I saw the "Deny all" .htaccess file that resides in application and system folders but i don't want to remove that either (if it's causing the problem) :D

I saw the "Deny all" .htaccess file that resides in application and system folders but i don't want to remove that either (if it's causing the problem) :D

It's good that you don't want to remove that, it's helping to keep your application (and sensitive info like DB passwords) inaccessible over http. However, that's exactly the reason you can't access javascript files this way.

You have to bite the bullet. Move the js files into an accessible directory.

I don't see any reason why you have to write the tags out manually if you are using PHP - you might want to look into writing or adopting some kind of template/asset library that other libraries can "hook into" and dynamically add js/css to the template.

Quick example:

class Template {

    private $js;

    function add_js($src)
    {
        $this->js[] = $src;
    }

    function get_js()
    {
        $out = '';
        foreach ($this->js as $src)
        {
            $out .= '<script src="'.$src.'"></script>';
        }
        return $out;
    }

}
  • Make sure Grid can access the CI instance. The most common method: assign a reference to a class property of Grid in the __construct() .

     $this->CI =& get_instance(); 
  • Add the script from your Grid library:

     $this->CI->template->add_js('/path/to/grid.js') 
  • In your HTML template, call $this->template->get_js() to print the tags

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM