【问题标题】:Ruby JSON Multi-Word Strings Rendered Incorrectly in HTMLRuby JSON 多字字符串在 HTML 中呈现不正确
【发布时间】: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&quot;}}>

# 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


【解决方案1】:

如果您跳过浏览器对“HTML”的解释并直接查看源代码,您应该会看到如下内容:

<section data-hash={&quot;subhash&quot;:{&quot;single&quot;:&quot;word&quot;,&quot;double&quot;:&quot;two words&quot;}}>

至少这是我使用 Rails4.2 得到的。这也给了我在 DOM 检查器中查看 HTML 时看到的相同结果。

浏览器将其视为:

<section data-hash={"subhash":{"single":"word","double":"two words"}}>

并试图将其理解为 HTML,但作为 HTML 没有意义,因此浏览器只会感到困惑。

如果您自己添加外引号:

<section data-hash="<%= @hash %>">
                   ^            ^

然后你会在 HTML 中得到这个:

<section data-hash="{&quot;subhash&quot;:{&quot;single&quot;:&quot;word&quot;,&quot;double&quot;:&quot;two words&quot;}}">

并且引号将被正确解释,因为 &amp;quot;s 将被视为 data-hash 属性的 HTML 编码内容,而不是对 HTML 属性的奇怪尝试。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-07-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多