JSON 与 Rails
有人请帮忙解决这个问题!!!
我试图简单地在 Rails 中用 javascript 解析我的 json 对象,但似乎没有任何效果。
控制器中的故事是:
def map
@nodes = Node.all
@json = {"Nodes" => @nodes.as_json(:only => [:ID, :Lat, :Lon])}
end
在我看来,我有简单的 javascript:
<script type="text/javascript">
var stuff = <%= @json %>;
var json = JSON.parse(stuff);
alert("text");
</script>
我只是想看看代码是否通过前两行运行并带有警报消息,但它永远不会工作,总是向我抛出意外的令牌错误(通常是冒号或 {)。我也尝试过使用 eval 方法,但这也不起作用。有人可以帮我解析javascript中的json吗?我将永远感激不已......
Someone please help with this!!!
I'm trying to simply parse my json object in javascript within rails, and NOTHING seems to work.
The story is in the controller is:
def map
@nodes = Node.all
@json = {"Nodes" => @nodes.as_json(:only => [:ID, :Lat, :Lon])}
end
In my view, I have simple javascript:
<script type="text/javascript">
var stuff = <%= @json %>;
var json = JSON.parse(stuff);
alert("text");
</script>
I'm just trying to see if the code runs through the first two lines with alert message, but it never works, always throwing me a unexpected token error (usually a colon or a { ). I've also tried doing the eval method, but that also doesn't work. Can someone please help me parse the json in the javascript? I would be eternally grateful....
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以采用当前的方法,需要进行一些修正才能使其工作
@json 这里不是 json,它是一个散列,当您将其分配给 javascript 变量时,它看起来像
stuff = {"Nodes" => javascript 中不接受此处的 => 节点值}
,因此它不是有效的 json 对象。你需要像这样转换 json 中的哈希对象
you can go with your current approach, there are few correction that you need to make it work
@json is not a json here, its a hash and when you assign it to javascript variable it looks like
stuff = {"Nodes" => node value}
here => is not accepted in javascript, thus its not a valid json object.you need to convert hash object in json like
查看 http://guides.rubyonrails.org/layouts_and_rendering.html 渲染 json 部分。
Check this out http://guides.rubyonrails.org/layouts_and_rendering.html The rendering json section.