0

foo.html.erb

<script type="text/javascript">
   var all_user = <%= @user.all_user_bar_chart.to_json.html_safe) %>;
</script>

abc.js

$(function () {
 if ($("#foo").length > 0){
     var user_charts = new Highcharts.Chart({
        chart: {
            renderTo: 'foo'
        },
        title: {
            text: 'User Statistics',
            x: -20 //center
        },
        subtitle: {
            text: ' ',
            x: -20
        },
        xAxis: {
            categories: ['a', 'b', 'c', 'd']
        },
        yAxis: {
            title: {
                text: 'point'
            },
            plotLines: [{
                value: 0,
                width: 1,
                color: '#808080'
            }]
        },
        tooltip: {
            valueSuffix: '°C'
        },
        legend: {
            layout: 'vertical',
            align: 'right',
            verticalAlign: 'middle',
            borderWidth: 0
        },
        series: all_user
    });
    console.log(all_user);
  }
});

这里输出形式模型数据或 foo.html.erb :-
"[{\"name\":\"A\",\"data\":94},{\"name\":\"b\" ,\"data\":356},{\"name\":\"c\",\"data\":1}]"

我想删除(“”)双引号并根据`highcharts'支持此数据以获得用户的基本折线图。我也试过 JSON.parse 但它不工作。每次得到字符串 "[{\"name\":\"A\",\"data\":94}]" 的结果

4

1 回答 1

0

to_json结果是字符串,您需要 javascript 对象哈希。

在 highchart 中,您可以将series属性设置为对象而不是字符串,因此您需要该字符串中的一个对象,才能在 javascript 中使用它:

series: JSON.parse(all_user)

前任:

test = "[{\"name\":\"A\",\"data\":94},{\"name\":\"b\",\"data\":356},{\"name\":\"c\",\"data\":1}]"
JSON.parse(test)
# it will return 
[{name: "A", data: 94}, {name: "b", data: 356}, {name: "c", data: 1}]
于 2013-10-15T10:11:39.433 回答