从 Ruby 返回一个 javascript 对象
我们从 ruby 代码返回以下 JSON:
{
"label":"CPU-7",
"data":[[50,45,38,34]],
"settings":{
"seriesDefaults":{
"renderer":"$.jqplot.BarRenderer"
},
"axes":{
"xaxis":{
"renderer":"$.jqplot.CategoryAxisRenderer",
"ticks":[50,45,38,34]
}
}
}
}
但是,“$.jqplot.BarRenderer”是一个对象,我们不希望它作为字符串返回,有没有办法做到这一点?
We are returning the following JSON from a ruby code:
{
"label":"CPU-7",
"data":[[50,45,38,34]],
"settings":{
"seriesDefaults":{
"renderer":"$.jqplot.BarRenderer"
},
"axes":{
"xaxis":{
"renderer":"$.jqplot.CategoryAxisRenderer",
"ticks":[50,45,38,34]
}
}
}
}
However, "$.jqplot.BarRenderer" is an object and we don't want it to be returned as string, is there a way to do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我认为这是不可能的。 JSON 是一个简单的哈希,而 ruby 不能包含 javascript 对象,并且没有办法(afaik)来
eval
部分 JSON。所以我建议类似的东西,让服务器渲染一个
chart.js.erb
而不是 JSON,并将其放置在您编写完整的$.jqplot
函数的部分中。I do not think that is possible. JSON is a simple hash, and ruby can not include javascript object, and there is no way (afaik) to
eval
parts of the JSON.So i would suggest something similar, and let the server render a
chart.js.erb
instead of JSON, and place the inside the partial you write the complete$.jqplot
function.这并不能直接回答您的问题,而是提供了替代方案。如果您绝对必须执行您想要的操作,请参阅下面的注释
您可能不希望您的 ruby 代码了解有关您的 javascript 对象的任何信息。相反,您可以维护某种
type
结构,这样如果您返回的数据是barChart
类型,您就可以通过这种方式引用它。类似这样的事情:那么如果你返回:
你可以使用
再次,我会避免让你的 ruby 了解有关你的 javascript 对象或你如何实际渲染数据的任何信息。 Ruby 应该只提供数据,javascript 选择如何处理它。
注意
要从 json 字符串中获取实际对象,只需执行以下操作
This doesn't directly answer your question but gives an alternative. See my note below though if you absolutely must do what you're wanting
You probably don't want your ruby code to know anything about your javascript objects. Rather you can maintain some sort of
type
structure such that if you returned data is of typebarChart
you can reference it that way. SOmething like:Then if you returned:
You can use
Again, I'd avoid having your ruby know anything about your javascript objects or how you're actually rendering the data. Ruby should just provide the data, javascript chooses what to do with it.
note
to get an actual object from your json string, just do
在你看来尝试原始方法。它将按原样呈现数据。
Upadte:
您是否像这样在控制器中渲染数据?
Try raw method in your view. It will render the data as it is.
Upadte:
Are you rendering data in controller like this?