在rails上加載JSON數據以使用HIGHCHARTS

[英]Loading JSON data in Ruby on rails to use HIGHCHARTS


I want to load a JSON data in RoR 4 to graphic the data using Highcharts. I have in index.html.erb

我想在RoR 4中加載JSON數據以使用Highcharts對數據進行圖形化。我在index.html.erb

{<h1 style="text-align:center" >HighCharts Test</h1>
<h1>Start</h1>
<div id="container" style="width:100%;height:400px;"></div>
<script>
   $(document).ready(function() {

    var options = {
        chart: {
            renderTo: 'container',
            type: 'spline'
        },
        series: [{}]
    };

    $.getJSON('data.json', function(data) {
        options.series[0].data = data;
        var chart = new Highcharts.Chart(options);
    });

});
</script>
<h1>End</h1>}

The data.json is in the same folder as index.html.erb.

data.json與index.html.erb位於同一文件夾中。

However, it is not plotting anything when i run the code. Im very new to RoR and Highcharts. Whats the error? Thank you.

但是,當我運行代碼時,它沒有繪制任何內容。我是RoR和Highcharts的新手。是什么錯誤?謝謝。

2 个解决方案

#1


You need to create a controller, let say ChartsController. and write following method in charts_controller.rb

你需要創建一個控制器,比如說ChartsController。並在charts_controller.rb中編寫以下方法

def data
  # this method is to send manually json data 
  #render json: {name: 'test',data: [2,0,9,23,2,123]}
  # or read data from a data.json file, use your custom path
  data = File.read("#{Rails.root}/app/views/charts/data.json")
  render json: data
end

and, in your view write this code.

並在您的視圖中編寫此代碼。

<script src="/assets/jquery.js"></script>
<script src="http://code.highcharts.com/stock/highstock.js"></script>
<script src="http://code.highcharts.com/stock/modules/exporting.js"></script>
<h1>Start</h1>
<div id="container" style="width:100%;height:400px;"></div>
<script>  

$(document).ready(function() {
    options = {
        chart: {
            renderTo: 'container',
            type: 'spline'
        },
        series: [{}]
    };
    $.getJSON('data.json', function(data) {
        options.series = data;
        new Highcharts.Chart(options);
    });

});

<h1>End</h1>

I have tried, it works at my side, hopefully it work successfully.

我試過了,它在我身邊工作,希望它成功地運作。

#2


Haven't worked with RoR yet, but my best guess will be that either your json file should be in the assets folder. (or some other folder used for static files).

還沒有使用過RoR,但我最好的猜測是你的json文件應該在assets文件夾中。 (或用於靜態文件的一些其他文件夾)。

The other way around (the right way, I believe) will be to have a separate controller, that will render you json file after you have requested it via js code. See this question: getting data using jquery getJSON in ruby on rails

反過來(正確的方式,我相信)將有一個單獨的控制器,將通過js代碼請求它后呈現json文件。看到這個問題:在rails上的ruby中使用jquery getJSON獲取數據


注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2015/05/13/f8dd25493979e03d32b0d1e21d0be81a.html



 
  © 2014-2022 ITdaan.com 联系我们: