Rails不能以json格式输出数据
Rails won't output data in json
这简直要把我逼疯了
我需要链接的格式为
links = [{source: 1, target: 2}, {..}, ...]
控制器代码: @edges = []
Follow.where("followable_type= 'User'").map do |x|
@edges << {source: x.follower_id, target: x.followable_id}
end
查看代码(javascript内部):
var links = [(<%= @edges.to_json %>)];
在HTML源码中的输出是
var links = [([{"source":2,"target":3},{"source":2,"target":1},{"source":8,"target":1},{"source":1,"target":8},{"source":17,"target":13},{"source":8,"target":13},{"source":8,"target":3},{"source":13,"target":3},{"source":3,"target":2},{"source":39,"target":13},{"source":3,"target":39},{"source":15,"target":1},{"source":1,"target":15},{"source":3,"target":1},{"source":3,"target":8},{"source":3,"target":13},{"source":21,"target":3},{"source":13,"target":21},{"source":13,"target":39},{"source":21,"target":13},{"source":21,"target":27},{"source":27,"target":13},{"source":1,"target":3},{"source":1,"target":39},{"source":1,"target":2},{"source":1,"target":13},{"source":1,"target":21},{"source":1,"target":27}])];
所以我想我应该把html_safe放在那里。这就得到
var links = [([{"source":2,"target":3},{"source":2,"target":1},{"source":8,"target":1},{"source":1,"target":8},{"source":17,"target":13},{"source":8,"target":13},{"source":8,"target":3},{"source":13,"target":3},{"source":3,"target":2},{"source":39,"target":13},{"source":3,"target":39},{"source":15,"target":1},{"source":1,"target":15},{"source":3,"target":1},{"source":3,"target":8},{"source":3,"target":13},{"source":21,"target":3},{"source":13,"target":21},{"source":13,"target":39},{"source":21,"target":13},{"source":21,"target":27},{"source":27,"target":13},{"source":1,"target":3},{"source":1,"target":39},{"source":1,"target":2},{"source":1,"target":13},{"source":1,"target":21},{"source":1,"target":27}])];
更好,但是每个键都是字符串。而且不能是string
我怎样才能使它工作?问题出在控制器还是视图?
JSON中没有符号的概念(和Ruby一样)。键必须是JSON格式的字符串。在你的情况下,你似乎不需要钥匙。你可以只使用follower id和followable id的数组。
相关文章:
- 以不同的顺序输出数据
- 如何在客户端输出数据?(express+monodb+jade)
- 使用AJAX获取JSON数据,然后通过HTML上的ElementID输出数据
- 使用 jQuery 遍历 JSON 数组并输出数据
- 在输出数据之前,等待循环完成每个数组项的 $.getJSON
- AJAX JQUERY 代码的哪一部分确定输出数据的占位符
- jQuery/Js 循环使用 Codeigniter MySQL 输出数据
- 角度可编辑滤波器输入和输出数据
- 使用javascript确定一个数组提交按钮,然后使用Ajax输出数据
- JS Json代码没有在视图源上输出数据
- Meteor Template不会在每个语句中输出数据
- 如何循环使用条件遍历JavaScript对象,然后输出数据
- 使用esc_js()保存的输出数据
- 获取从下拉菜单中选择的每个用户要更改的输出数据
- 从AJAX调用输出数据到HTML
- Rails不能以json格式输出数据
- 是否有可能从这些不以HTML源代码输出数据的网站中提取数据?
- 使用JavaScript从XML文件搜索和输出数据
- 从TaffyDB输出数据
- HTML客户端接收连续的服务器输出数据流