简体   繁体   中英

Pass data from Controller to Javascript in Rails

I am trying to use Google Charts API following this example Google Charts Quick Start

As you see the data is created in the JS as:

data.addColumn('string', 'Topping');
        data.addColumn('number', 'Slices');
        data.addRows([
          ['Mushrooms', 3],
          ['Onions', 1],
          ['Olives', 1],
          ['Zucchini', 1],
          ['Pepperoni', 2]
        ]);

My question is:

If in my controller I get data... How can I pass it to the Javascript of my template file? I have this example JS hooked up in the head of my index.html.erb file.

You would just need to create a ruby variable in your controller action to hold your values and generate the javascript in the view using them values using <%= %> tags.

Example: @values would be a name value collection.

data.addColumn('string', 'Topping');
data.addColumn('number', 'Slices');
data.addRows([
    <% @values.each do |v| %>
        ['<%= v.name %>', <%= v.value %>],
    <% end %>
    ]);

Example using a js function.

index.js:

var values;

function InitPage(valuesFromView)
{
    values = valuesFromView;
}

function InitData()
{
    data.addColumn('string', 'Topping');
    data.addColumn('number', 'Slices');
    data.addRows(values);
}

index.html.erb: Note that I'm using jquery to call InitPage when the page loads, if you're not using jquery your InitPage call would probably be in the onload of the body tag or something similar.

<script>
    $(document).ready(function() {
        InitPage([
           <% @values.each do |v| %>
               ['<%= v.name %>', <%= v.value %>],
           <% end %>
        ]);
    });
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM