2012-08-13 51 views
0

我正在尝试使用Google Chart Tools绘制图表。将数据传递给Google Chart工具

google.load("visualization", "1", {packages:["corechart"]}); 
    google.setOnLoadCallback(drawChart); 
    function drawChart() { 
    var data = new google.visualization.DataTable(); 
    data.addColumn('number', 'Month'); 
    data.addColumn('number', 'Money'); 
    data.addRows([ 
     [<%= @months %>, <%= @money %>] 
     ]); 

    var options = { 
     title: 'Title' 
    }; 

    var chart = new google.visualization.LineChart(document.getElementById('chart_div_2')); 
    chart.draw(data, options); 
    } 

@months和@money是数组。不幸的是,我可能无法以这种方式传递数组,因为图表不显示。什么是正确的处理这种情况?

UPDATE

好了,我用刚和setCell功能在for循环和它的作品

回答

0

使用JSON。 respond_to块可用于此目的。返回包含数据值数组的json散列。

def months_monies 
    respond_to |format| 
    format.json {render :json => @post} 
    # The post is a Ruby hash that gets converted into json string 
    format.html #months_monies.html.erb 
    end 
end 

考虑一个例子,其中@post变量是,说{:a => {"January" => 1000}, :b => {"April" => 1222}}

这可以从JavaScript的块通过使AJAX调用使用jQuery访问以http://localhost:3000/months_monies.json

实施例:

$.get("http://localhost:3000/controller/months_monies.json",function(post){ 
    post.a.January # => 1000 
    post.b.April # => 1222 
}); 

如果@post变量是一个数组(在你的情况下最可能如果是这种情况),该方法几乎相似。说@post = [{'january' => 1000}, {'february' => 1111}]

然后,您将使用post[0].januarypost[1].february获取$.get块中的值。

希望有所帮助。

+0

我可以使用[坤](https://github.com/gazay /坤)而不是JSON?如果,是的,我可以在图表代码中使用我的@post作为gon.post,但是有没有可能通过并使用整个数组,而不引用单个数组元素? – matyyyy 2012-08-13 20:05:24

+0

尝试使用'Gon'模块。没有随时使用它,所以不能确定。我在示例中使用了一个散列,以便清楚数据表示如何转换。你可以传递整个数组。 '@post = {@months => [...],@money => [...]}'将被转换为这个json对象:'{'months':[']'money': [012]} – Kashyap 2012-08-14 08:37:13

+0

如果您可以显示数据样本,我会将其添加到答案 – Kashyap 2012-08-14 08:37:39