Rails 3 passing a rails array to javascript function which uses a javascript array

前端 未结 5 984
悲哀的现实
悲哀的现实 2021-02-18 18:12

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

5条回答
  •  一个人的身影
    2021-02-18 19:02

    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"}}]

    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
    

    Then passed chart_values() to the javascript.

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

提交回复
热议问题