我可以使用JSON对象和jQuery-Rails(jQuery库加上一个特殊的rails.js文件)对Rails(3)进行典型的Ajax调用.

In one controller, though, I want to RETURN some JSON in an erb template (create.js.erb) after an AJAX call.

我try 了控制器中的所有组合(@object.to_json、‘[{"content":"hello world"}]’等).和模板本身(JSON.parse()、单引号、双引号等),但对象继续以如下方式呈现:

'[{"groups":{},"created_at":"2010-09-21T03:49:34Z" ...

and as a result, my jQuery code cannot parse it and I get errors.

How do I need to prep my object in the controller, and what erb syntax do I need in the view for it to render as a valid JSON object?

非常感谢!

推荐答案

I'm not sure this is the cause, but you can also try playing around with html_safe method. ERB might be escaping your JSON because it thinks it's not html safe. Try calling that method when using the string:

@object.to_json.html_safe

Json相关问答推荐

使用Jolt将字符串数组转换为JSON对象数组

最新版本的Deneb在数据溢出时不支持滚动

通过在织女星简化图上裁剪来显示文本

交换键和数组值,将旧键转换为新数组值,使用 jq

Vega-Lite规范:尽管在规范中提供了数据,但显示空图表

使用 jq 将非统一的 json 输出转换为汇总表

将=分隔值文件转换为:json文件

在 CodePipeline 中调用 lambda 时传递用户参数

jq可以在两个JSON对象列表中依次添加对象吗?

嵌套 JSON 到 CSV(多级)

jq搜索特定字符串并输出对应的父值

使用 jq 将键值行转换为 json

json.decoder.JSONDecodeError:期望值:第 1 行第 1 列(字符 0)

将 Objective-C 对象序列化和反序列化为 JSON

区分字符串和列表的 Pythonic 方式是什么?

在浏览器中查看 JSON 文件

Sequelize - 如何仅返回数据库结果的 JSON 对象?

MVC JsonResult camelCase 序列化

通过 JSON 发送 64 位值的公认方式是什么?

如何在 React js 中解析本地 JSON 文件?