2012-08-13 49 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