Ruby JSON 多字字符串在 HTML 中呈现不正确
Ruby JSON Multi-Word Strings Rendered Incorrectly in HTML
我的多词字符串在 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" 的解释并直接查看源代码,您应该会看到如下内容:
<section data-hash={"subhash":{"single":"word","double":"two words"}}>
至少这就是我使用 Rails4.2 得到的。当我在 DOM 检查器中查看 HTML 时,这也给了我相同的结果。
浏览器将其视为:
<section data-hash={"subhash":{"single":"word","double":"two words"}}>
并试图将其理解为 HTML 但这没有意义 HTML 所以浏览器会感到困惑。
如果自己加上外引号:
<section data-hash="<%= @hash %>">
^ ^
然后你会在 HTML:
中得到这个
<section data-hash="{"subhash":{"single":"word","double":"two words"}}">
引号将被正确解释,因为 "
将被视为 data-hash
属性的 HTML 编码内容,而不是对 [=31 的奇怪尝试=] 属性.
我的多词字符串在 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" 的解释并直接查看源代码,您应该会看到如下内容:
<section data-hash={"subhash":{"single":"word","double":"two words"}}>
至少这就是我使用 Rails4.2 得到的。当我在 DOM 检查器中查看 HTML 时,这也给了我相同的结果。
浏览器将其视为:
<section data-hash={"subhash":{"single":"word","double":"two words"}}>
并试图将其理解为 HTML 但这没有意义 HTML 所以浏览器会感到困惑。
如果自己加上外引号:
<section data-hash="<%= @hash %>">
^ ^
然后你会在 HTML:
中得到这个<section data-hash="{"subhash":{"single":"word","double":"two words"}}">
引号将被正确解释,因为 "
将被视为 data-hash
属性的 HTML 编码内容,而不是对 [=31 的奇怪尝试=] 属性.