Codeigniter - 如何在视图中包含动态JavaScript文件 [英] Codeigniter - how to include a dynamic javascript file in a view

查看:143
本文介绍了Codeigniter - 如何在视图中包含动态JavaScript文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果满足某些条件,我想在我的标题视图中包括以下代码块(其中包含一些动态值)。

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

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();
}


推荐答案

控制器并将其传递给控制器​​。

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

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

请注意,第三个参数设置为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);

这是一个更好的MVC方法,因为逻辑保留在控制器中。

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

这篇关于Codeigniter - 如何在视图中包含动态JavaScript文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆