Codeigniter - how to include a dynamic javascript

2019-02-20 11:20发布

问题:

I'm trying to include the following code block (which contains some dynamic values) in my header view if certain conditions are met.

<script src="<?php echo base_url();?>assets/jquery.Jcrop.js"></script>
<link rel="stylesheet"  href="<?php echo base_url();?>assets/jquery.Jcrop.css" />
<script type="text/javascript">
    <?php if (isset($load_jcrop_api) && $load_jcrop_api === TRUE) {?>
        // Javascript 1
    <?php } else { ?>
        // Javascript 2
    <?php } ?>
</script>

I've done some reading up and I started to try the following but I get an error trying to call this function from within a view so I'm a bit stuck on the best way to appoach this.

CONTROLLER

function get_jcrop_ini() {
    $this->output->set_header('Content-type: text/javascript');
    $data = array( 'messages' => $this->session->flashdata('message'));
    $this->load->view('jcrop_ini',$data);
}

VIEW

if (isset($load_jcrop) && $load_jcrop === TRUE) {
    $this->get_jcrop_ini();
}

回答1:

Load the JS view in the controller and pass it over to the controller.

$jsview = $this->load->view('view_name', array(), true);

Note that the third parameter is set to true. That will return the view to you instead of outputting the view to the screen.

Then, pass it over to your main view.

$data['js'] = $jsview;

$this->load->view('mainview',$data);

That is a better MVC approach as the logic remains in the controller.