Rails 3将Rails数组传递给使用JavaScript数组的javascript函数 [英] Rails 3 passing a rails array to javascript function which uses a javascript array

查看:71
本文介绍了Rails 3将Rails数组传递给使用JavaScript数组的javascript函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将Rails数组传递给javascript函数.然后,该函数将使用javascript中的数组值,因此我需要将其保留为数组.

I am trying to pass a rails array to a javascript function. The function will then use the array values in javascript so I need to keep it an array.

这是我传递数组的方式:

Here is how I am passing my array:

"graphit([<%=@mpg_values.join(",") %>])"

这会在HTML中生成

"graphit([#&lt;Mile:0x6ff0cf0&gt;,#&lt;Mile:0x6ff0c18&gt;,#&lt;Mile:0x6ff0b58&gt;])"

不是值,它们应该是十进制数.我认为这是因为它是对数组的引用,所以我为什么要弄乱值.如果我做类似to_s的操作,我会看到这些值,但其中还包含其他内容,例如表和文件名.

Which are not the values, they should be decimal numbers. I assume this is because it is a reference to the array so that I why I am getting the messed up values. If I do something like to_s I see the values but it has other stuff like the table and filed name in there as well.

有人知道如何将这个rails数组作为数组传递给javascript函数吗?

Anybody know how I can get this rails array to a javascript function as an array?

在此先感谢您的帮助.

推荐答案

在这篇文章中几次建议使用JSON总是给我这样的感觉.

Going to JSON as suggested a couple times in this post always gave me something like this.

[{"mile":{"date":"2011-05-20","mpg":"18.565887006952"}},{"mile":{"date":"2011-06-01","mpg":"18.471164309032"}}]

[{"mile":{"date":"2011-05-20","mpg":"18.565887006952"}},{"mile":{"date":"2011-06-01","mpg":"18.471164309032"}}]

我真正想要的只是这个... [[2011-05-20,18.56] [2011-06-01,18.47]]

What I really wanted was just this... [[2011-05-20, 18.56][2011-06-01, 18.47]]

所以我用这样的助手来处理它.

So I handled it with a helper like so.

  def chart_values()
    @chart_values = '['
    @mpg_values.each do |m|
      @chart_values = @chart_values+'['+m.date.to_s+', '+m.mpg.round(2).to_s+'],'
    end
    @chart_values = @chart_values+']'
  end

然后将chart_values()传递给javascript.

Then passed chart_values() to the javascript.

可能不是最好的解决方案,但它以我所需的格式为我提供了所需的值.

Likely not the best solution but it gave me the desired values in the format I needed.

这篇关于Rails 3将Rails数组传递给使用JavaScript数组的javascript函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆