I'm trying to generate a chart in my Rails 3 project using the canvasXpress HTML5 / JavaScr开发者_运维问答ipt library. Their charting API uses JSON as one of the parameters in their constructor. For example:
new CanvasXpress('canvas', /* JSON here */);
In Rails I'll have a view which renders the chart as part of it's overall output. So, the JavaScript to create the chart will live in the view.
I'm not quite sure how to have Rails generate the JSON the JavaScript needs. Should the JSON be generated in a partial view?
In any case, an example would be nice.
The route I took in a similar situation was to use two view files (one action) and two requests to render 1st the page, then 2nd the json/data for a graph. (I am using using the wonderful HighCharts library)
In our case ensuring that the page loaded (with all nav, options etc) before the potentially heavy/long data processing required to provide the json was important. It also gave us the benefit of a view just for the JSON.
Controller:
def show
@graph = Graph.find(id)
respond_to do |format|
format.html do
@variable_needed_for_html_layout = current_user.graphs
end
format.js do
@data = @graph.process_data
end
end
end
The html view(show.html.erb) just renders all the html markup and makes an ajax request(jquery) for the js:
<script type='text/javascript'>
$(document).ready(function(){
$.getScript('<%= graph_path(@graph, :js) -%>');
});
</script>
<div id="highchart"></div>
The js view(show.js.erb) then does all the heavy lifting:
var chart = new Highcharts.Chart({
chart: {
renderTo: 'highchart',
}
...
});
精彩评论