How do I include jQuery file in CodeIgniter?

2019-05-04 19:30发布

问题:

I would like to use jQuery inside my CodeIngiter Project. I dont know how to include the js file.

I would like to have something like below in my view

<script src='<?php echo base_url().APPPATH ?>js/jquery.js'></script>
<script src='<?php echo base_url().APPPATH ?>js/my-js.js'></script>

回答1:

Firstly, create a folder to put it in. Then you could use a template system like this one.

This lets you add js files either globally in the main template, or by a controller/function basis using the syntax $this->template->add_js('assets/js/jquery.js');



回答2:

Codeigniter has a javascript class: http://codeigniter.com/user_guide/libraries/javascript.html

You would load the jquery library through:

$this->load->library('jquery');

Then you can paste this into your head section of your view:

<?php echo $library_src;?>
<?php echo $script_head;?>

For additional javascript files, I typically create a resource folder in my application folder, then use the base_url function to link to the files like:

<script src="<?php echo base_url('resources/name-of-js-file.js');?>" type="text/javascript"></script>


回答3:

The base_url() requires to load the helper 'url'.

In order to archive that go to application/config/autoloader.php and add it on the variable $autoloader['helper'] like this:

$autoload['helper'] = array('url');


回答4:

add a new folder 'js' in your application folder and in your views add this line

<script type="text/javascript" src="<?php echo base_url();?>js/name of your js file"></script>


回答5:

You include the JS file like any other HTML output.

Refer to where your JS is located (say its /js from root) and then in your <head></head> portion add the following:

<script type="text/javascript" src="/js/jquery.min.js"></script>