0

我是 RoR 和 web 应用程序开发的新手,我使用 Rails 3.2.3,我想在 Highcharts 中使用 ruby​​ 数组,我在视图文件中使用 Haml。

我在控制器中定义了一个数组,如下所示:

...
def show
  ...
  @close_array = DailyQuote.where(company_id: @company.id).map(&:closing_price)
end

我已经在我的 Haml 视图文件中声明了它。

%body
  - close_array_j = "#{@close_array.inspect}"
  =javascript_include_tag :build_chart
  #container{:style => "min-width: 300px; height: 300px; margin: 0 auto"}

现在我想close_array_j在一个 Highcharts 图表中使用这个数组,我在一个名为 build_chart.js 的单独文件中编写了代码:

$(function () {
  var chart;
  $(document).ready(function() {
  chart = new Highcharts.Chart({
    chart: {
      renderTo: 'container',
      },
...
    series: [{
      name: 'Closing Price',
      data: $('#close_array_j')
    }]
...

正在呈现没有数据的 highcharts 图表。顺便说一句,我不太了解 ruby​​ 或 haml 或 js,你可能会说...

4

2 回答 2

4

您可以在 HAML 中像这样打印变量

%script
  != "close_array_j = #{@close_array.to_json};"

然后在javascript中使用它

...
series: [{
    name: 'Closing Price',
    data: close_array_j
}]
...
于 2012-09-03T02:15:32.833 回答
0

The variable assignment you do in your haml view file has no effect. It doesn't automagically apply itself in your javascript file.

You could wrap it up in a script tag. Here's the erb version:

<%= javascript_tag do %>
 close_array_j =  = '<%= j @close_array.to_json %>';
<% end %>

However, there are other, cleaner techniques. One would be to leverage the HTML5 data attribute to embed data such as yours. It's easy to access with Jquery.

I recommend you watch Ryan Bate's screencast on how to pass data to javascript in a variety of ways.

http://railscasts.com/episodes/324-passing-data-to-javascript?view=asciicast

于 2012-09-03T02:37:45.557 回答