将 JSON 从 ruby 辅助函数返回到 javascript
我有一个 Ruby on Rails 应用程序。单击按钮后,我会进行一些 AJAX 调用,这些调用应以 JSON 形式返回。
以下是相关的代码行:
File "index.js.erb":
var myJson = <%= chart_data %>;
File "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
问题是,当我从chart_data返回valRet2时,我在index.js.erb文件中获得了所需的数组。但如果我尝试返回 valRet1,则会出现错误。
我尝试了 ActiveSupport::JSON.encode、jQuery.parseJSON、将 JSON 对象转换为字符串并转义引号等。似乎没有任何效果。
以下导致错误:
return '[["Sep 9, 1970", 0],
["Sep 14, 1970", 0.94],
["Sep 20, 1970", 0.46]]'
以下也导致错误:
result = [['Sep 9, 1970', 0],
['Sep 14, 1970', 0.94],
['Sep 20, 1970', 0.46]]
return '"' + ActiveSupport::JSON.encode(result) + '"'
以下正确返回:
return "[['Sep 9, 1970', 0],
['Sep 14, 1970', 0.94],
['Sep 20, 1970', 0.46]]"
数组(最好是散列)需要动态创建(从数据库中获取值),因此不能是正确返回的文字数据如上。
帮助将不胜感激。
环境:
OS: Windows 7
Rails: 3.1.0
Ruby: 1.9.2p290 (2011-07-09) [i386-mingw32]
问候,
Imtiaz
I have a Ruby on Rails application. On click of a button I have some AJAX calls that should return with JSON.
Here are the relevant lines of code:
File "index.js.erb":
var myJson = <%= chart_data %>;
File "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. But if I try returning valRet1, I get errors.
I played around with ActiveSupport::JSON.encode, jQuery.parseJSON, converting my JSON object to string and escaping quotes etc. Nothing seems to work.
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用
:to_json
方法:对数组或控制器
Use
:to_json
method for Arrayor from controller:
好的。我发现以下方法有效:
所以问题部分解决了。仍在寻找一种解决方案来返回 jQuery / javascript 可以通过调用理解的 json 对象,例如:
Ok. I found that the following works:
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: