在Rails 4 JS/ERB模板中嵌入JSON [英] Embedding JSON in a Rails 4 JS/ERB template
问题描述
我正在尝试将模型数据嵌入到RoR 4应用程序中的某些javascript中.像这样,控制器正在为模型数据生成JSON ...
I'm trying to embed model data in some javascript in my RoR 4 app. The controller is generating JSON for the model data like so...
def my_controller_method
@person = Person.find(params[:id])
@person_json = @person.to_json(only: [:name, :id])
end
并且我想在我的不引人注意的javascript中使用该json来使用JSON.parse()创建javascript对象...
and I'd like to use that json in my unobtrusive javascript to create javascript objects using JSON.parse()...
var personJSON = <%= j @person_json %>;
var person = JSON.parse(personJSON);
但是生成的javascript是...
but the javascript that's generated is...
var personJSON = {\"id\":1,\"name\":\"fred\"};
var person = JSON.parse(personJSON);
并且javascript静默失败.
and the javascript is failing silently.
在寻找解决方案时,我发现在SO 上运行,但是当我尝试使用html_safe方法时,我的rails应用程序崩溃,并说html_safe是未知方法.
When searching for a solution, I found this question asked on SO, but when I try to use the html_safe method, my rails app crashes saying html_safe is an unknown method.
提前感谢您的帮助!
推荐答案
这是怎么回事:
var personJSON = <%= @person_json.to_json.html_safe %>
或
var personJSON = <%= raw @person_json %>
我认为对于您的特定情况,最后一种选择更好.
I think the last option is better for your particular case.
这篇关于在Rails 4 JS/ERB模板中嵌入JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!