处理JSON的JS / ERB模板中的Rails 3 [英] Handling JSON in JS/ERB template in Rails 3
问题描述
我没有问题使典型的AJAX调用和滑轨(3)使用JSON对象和jQuery护栏(jQuery库以及一个特殊的rails.js文件)。
在一个控制器,不过,我想一个AJAX调用后返回ERB模板(create.js.erb)一些JSON。
我试图事物每个组合在所述控制器(@ object.to_json,'[{内容:世界你好}]等)和在模板本身(JSON.parse(在),单引号,双引号,等等),但对象不断呈现这样的:
<$p$p><$c$c>'[{"groups":{},"created_at":"2010-09-21T03:49:34Z" ...和结果,我的jQuery code不能分析它,我得到的错误。
我如何需要$ P $页我的控制器中的对象,我需要在视图中为它呈现为一个有效的JSON对象?什么ERB语法
太感谢了!
我不知道这是原因,但你也可以尝试用 html_safe
玩弄方法。雇员再培训局可能会逃避,因为它认为它不是HTML安全的JSON。尝试使用字符串时,调用该方法:
@ object.to_json.html_safe
I have no trouble making typical AJAX calls to and from Rails(3) with JSON objects and jQuery-rails (jQuery library plus a special rails.js file).
In one controller, though, I want to RETURN some JSON in an erb template (create.js.erb) after an AJAX call.
I've tried every combination of things in the controller (@object.to_json, '[{"content":"hello world"}]', etc.) and in the template itself (JSON.parse(), single quotes, double quotes, etc.), but the object keeps on rendering like this:
'[{"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?
Thanks so much!
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的JS / ERB模板中的Rails 3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!