简体   繁体   中英

passing ruby arrays to javascript code (jquery) in a haml view in Ruby on Rails

I am displaying Highcharts graph on a haml template using jQuery/javascript. Here is a snippet showing the standalone graph from the demo code in HighCharts site:

:javascript

  $(document).ready(function() {
    $("#tabs").tabs();
    new Highcharts.Chart({
      chart: {
        renderTo: 'volume_chart'
      },
      title: {
        text: 'Logarithmic axis demo'
      },
      xAxis: {
        tickInterval: 1
      },
      yAxis: {
        type: 'logarithmic',
        minorTickInterval: 0.1
      },
      tooltip: {
        headerFormat: '<b>{series.name}</b><br />',
        pointFormat: 'x = {point.x}, y = {point.y}'
      },
      series: [{            
        data: [1, 2, 4, 8, 16, 32, 64, 128, 256, 512],
        pointStart: 1
      }]
    });
  });

This works fine. Now I am trying to set the series data from a ruby/rails array in the show.html.haml file like so:

...
- data_array        = [1, 2, 4, 8, 16, 32, 64, 128, 256, 512]
...
:javascript

  $(document).ready(function() {
  ...
      series: [{            
        data: "#{data_array}",
        pointStart: 1
      }]
    });
  }); 

This gives me the following error:

undefined method `to_js' for [1, 2, 4, 8, 16, 32, 64, 128, 256, 512]:Array

How can I pass data_array from my ruby/rails code to the javascript/jquery code?

Appreciate any help.

Thanks.

Bharat

require 'json'

...

"#{data_array.to_json}"

Hey in HAML there is no need to use to_json

   :javascript
     $(document).ready(function() {
       ...
       series: [{            
         data: #{ruby_array},
         pointStart: 1
       }]
     });
    }); 

will perfectly work

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