简体   繁体   English

Codeigniter-如何将JSON传递到资产文件夹中的JS文件?

[英]Codeigniter - How to pass JSON to JS file in assets folder?

I am trying to pass json from my cotroller to my JS in assets folder 我正在尝试将cotroller中的json传递到Assets文件夹中的JS

Here is my container.js : 这是我的container.js

Highcharts.chart('container', {
    chart: {
        type: 'column'
    },
    series: [{
        name: 'Umur',
        colorByPoint: true,
        data: <?php echo json_encode($based_on_age); ?>
    }],
  });

And here is my controller: 这是我的控制器:

public function index(){
    $sbow=array();

    foreach ($this->m_data->based_on_weeks()->result_array() as $row) {
        $sbow[]=array($row['range'],(float)$row['total']);
    }
    $data['based_on_weeks'] = $sbow;

    $this->load->assets?(container.js,$data); //is there a way to pass data to assets?
    $this->load->view('state.html');
}

I believe, you can simply pass your data to your view file. 我相信,您只需将数据传递到视图文件即可。 & you will have that data in your JS file as well. &您也将这些数据保存在JS文件中。 Just create a variable in your view file in script tag & it will be accessible in your `container.js' file 只需在脚本标记的视图文件中创建一个变量,即可在您的“ container.js”文件中访问

You can use like 你可以用像

var highChartData = <?php echo json_encode($data["based_on_weeks"])?>;

and in container.js, you can do 在container.js中,您可以

Highcharts.chart('container', {
    chart: {
        type: 'column'
    },
    series: [{
        name: 'Umur',
        colorByPoint: true,
        data: highChartData
    }],
  });

The way you are looking to do this won't work, as CodeIgniter is a PHP framework, and therefore runs on the server side, and the container.js file, being JavaScript is client side. 您要执行此操作的方法将不起作用,因为CodeIgniter是一个PHP框架,因此在服务器端运行,而作为JavaScript的container.js文件在客户端运行。 Putting data/content into client side items isn't something which is done, unless you build those files and server them dynamically each time. 将数据/内容放入客户端项不是一件容易的事,除非您每次构建这些文件并对其进行动态服务器处理。

Along with the answer from @AgamBanga, you could also do the following directly in your view file (though you either need to include that view each time, or have it in every view you want the chart: 除了@AgamBanga的答案外,您还可以直接在视图文件中执行以下操作(尽管您需要每次都包含该视图,或者在想要图表的每个视图中包含该视图:

Highcharts.chart('container', {
    chart: {
        type: 'column'
    },
    series: [{
        name: 'Umur',
        colorByPoint: true,
        data: <?php echo json_encode($data['based_on_weeks'])?>
    }],
  });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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