1

在 Rails 中,我正在查询数据库以构建 highcharts 的数据对象。

这是我的控制器的方法:

def build_data_for_chart
data_array = Array.new
@data_array_as_json = ''

@issues.each { 
  |issue| 
  # returns an array of KeyIssue objects for a given issue
  given_issue_array = KeyIssues.where(issue: issue).all
  a = Array.new

  #loop through each element extracting the timedate and % and add to new array
  given_issue_array.each {
    |entry|
    a.push([entry.datetime.utc.to_date, entry.percentage])
  }

  #build the hash for an individual issue
  temp_hash = {:name => issue, :data => a, :animation => false}

  #add the individual issue and all its data to a final array that contains all the issues.
  data_array.push(temp_hash)
} 

@data_array_as_json = data_array.to_json.html_safe

结尾

现在,我正试图在我的视图中将其提取到脚本中。

- - 脚本 - -

var data = $.parseJSON(<%= @data_array_as_json %>);

- - 脚本 - -

当我打印到控制台时,我可以看到对象及其所有数据。此外,当我打印到 html 时,输出看起来是正确的:

"[{\"name\":\"ABORIGINAL & NATIVE TITLE Issues\",\"data\":[[\"1993-11-01\",32],[\"1994-06-01\" ,27],[\"1994-09-01\",33],[\"1995-06-01\",26],[\"1995-09-01\",24],[\"1996 -01-01\",20],[\"1996-09-01\",27],[\"1997-01-01\",33],[\"1997-06-01\",36 ],[\"1997-09-01\",36],[\"1998-01-01\",37],[\"1998-05-01\",33],[\"1998-09 -01\",31],[\"1999-05-01\",30],[\"1999-09-01\",28],[\"2000-01-01\",30], [\"2000-05-01\",31],[\"2000-09-01\",34],[\"2001-01-01\",32],[\"2001-06-01 \",29],[\"2001-09-01\",28],[\"2002-02-01\",25],[\"2002-06-01\",27],[\ "2002-10-01\",25],[\"2003-02-01\",24],[\"2003-06-01\",26],[\"2003-10-01\",27],[\"2004-02-01\",27],[\"2004-06-01\", 26],[\"2005-06-01\",30],[\"2006-06-01\",27],[\"2007-06-01\",31],[\"2008- 07-01\",29]],\"动画\":false}]"

但是当我去打印数据变量时它是空的(显然是由于不是有效的输入)。我在搞砸什么?

4

2 回答 2

1

供参考..

我需要用单引号括起来.. 让它工作..

$.parseJSON(' <%= @data_array_as_json %> ');
于 2013-10-25T03:30:49.127 回答
0

你可以试试这个:

<script type="text/javascript">
  var data = <%== data_array.to_json %>
</script>
于 2013-10-21T13:19:57.487 回答