简体   繁体   English

从ruby helper函数返回JSON到javascript

[英]returning JSON from ruby helper function to javascript

I have a Ruby on Rails application. 我有一个Ruby on Rails应用程序。 On click of a button I have some AJAX calls that should return with JSON. 单击按钮后,我有一些应该以JSON返回的AJAX调用。

Here are the relevant lines of code: 以下是相关的代码行:

File "index.js.erb": 文件“ index.js.erb”:

var myJson = <%= chart_data %>;

File "parameter_helper.rb": 文件“ parameter_helper.rb”:

module ParameterHelper
  def chart_data
    valRet1 = {
      :name => "Total Traffic",
      :data => [
        ['Sep 9, 1970', 0],
        ['Sep 14, 1970', 0.94],
        ['Sep 20, 1970', 0.46]

    ]
    }

    valRet2 = [1, 2]

    return valRet1

  end
end

The problem is that when I return valRet2 from chart_data, I get the required array in the index.js.erb file. 问题是,当我从chart_data返回valRet2时,我在index.js.erb文件中获得了所需的数组。 But if I try returning valRet1, I get errors. 但是,如果我尝试返回valRet1,则会收到错误消息。

I played around with ActiveSupport::JSON.encode, jQuery.parseJSON, converting my JSON object to string and escaping quotes etc. Nothing seems to work. 我玩了ActiveSupport :: JSON.encode,jQuery.parseJSON,将JSON对象转换为字符串并转义了引号等。似乎什么都没用。

The following resulted in errors: 以下导致错误:

return '[["Sep 9, 1970", 0],
        ["Sep 14, 1970", 0.94],
        ["Sep 20, 1970", 0.46]]'

The following also resulted in errors: 以下还导致错误:

result = [['Sep 9, 1970', 0],
          ['Sep 14, 1970', 0.94],
          ['Sep 20, 1970', 0.46]]
return '"' + ActiveSupport::JSON.encode(result) + '"'

The following returned correctly: 以下内容正确返回:

return "[['Sep 9, 1970', 0],
        ['Sep 14, 1970', 0.94],
        ['Sep 20, 1970', 0.46]]"

The array (preferably hash) needs to be made on the fly (taking values from database) and hence cannot be a literal as in the case of correctly returned data above. 数组(最好是哈希)需要动态生成(从数据库获取值),因此不能像上面正确返回的数据那样是文字。

Help will be appreciated. 帮助将不胜感激。

Environment: 环境:

OS: Windows 7
Rails: 3.1.0
Ruby: 1.9.2p290 (2011-07-09) [i386-mingw32]

Regards, 问候,

Imtiaz Imtiaz

Use :to_json method for Array 对数组使用:to_json方法

valRet1.to_json

or from controller: 或从控制器:

respond_to do |format|
  format.json do
    render :json => valRet1
  end
end

Ok. 好。 I found that the following works: 我发现以下作品:

valRet2 = [["'Sep 9, 1970'", 0],
  ["'Sep 14, 1970'", 0.94],
  ["'Sep 20, 1970'", 0.46]]

So the problem is partially solved. 因此,该问题已部分解决。 Still looking for a solution to return a json object that jQuery / javascript can understand by a call such as: 仍在寻找一种解决方案来返回jQuery / javascript可以通过以下调用理解的json对象:

var returnedJson = <%= chart_data %>;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM