【发布时间】:2015-04-11 03:54:07
【问题描述】:
我的多词字符串在 DOM 中没有被正确解释。如何使用多字字符串确保从服务器到 HTML 的 JSON 完整性?
在 Rails 控制器中,我将 JSON 对象存储在一个变量中。当我检查服务器日志时,该对象的格式正确。然后通过 erb 将该变量传递给视图中的数据属性。但是,生成的 HTML 不正确。
# in the controller
@hash = {'subhash' => {'single' => 'word', 'double' => 'two words' } }.to_json
puts @hash.inspect
# output in the server log
=> "{\"subhash\":{\"single\":\"word\",\"double\":\"two words\"}}"
# view.html.erb
<section data-hash=<%= @hash %> ></section>
# generated html, 'double' value is incorrect
<section data-hash="{"subhash":{"single":"word","double":"two" words"}}>
# complete data value is not obtainable in the console
> $('section').data().hash
< "{"subhash":{"single":"word","double":"two"
更新
# adding html_safe does not help
{"subhash" => {"single" => "word", "double" => "two words" } }.to_json.html_safe
# results in
"{"subhash":{"single":"word","double":"two" words"}}
【问题讨论】:
-
你在最后加了
.html_safe吗? -
是的。它使它看起来更好一些,但实际上并不能解决问题。
-
通过查看 Chrome 检查。
-
对不起,@muistooshort 我以为很清楚。我已经增强了示例,以尝试阐明代码以及重现所需的内容。
标签: html ruby json ruby-on-rails-4 ruby-2.2