开发者

Generate JSON in Rails for JavaScript object parameter

开发者 https://www.devze.com 2023-01-16 16:12 出处:网络
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 e

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',
    }
    ...
 });
0

精彩评论

暂无评论...
验证码 换一张
取 消