gpt4 book ai didi

html - Ruby JSON 多词字符串在 HTML 中呈现不正确

转载 作者:太空宇宙 更新时间:2023-11-03 18:14:27 29 4
gpt4 key购买 nike

我的多词字符串在 DOM 中没有被正确解释。如何确保从服务器到包含多词字符串的 HTML 的 JSON 完整性?

在 Rails Controller 中,我将一个 JSON 对象存储在一个变量中。当我检查服务器日志时,该对象的格式正确。然后该变量通过 erb 传递给 View 中的数据属性。但是,生成的 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”的解释并直接查看源代码,您应该会看到如下内容:

<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;}}">

并且引号将被正确解释为 " 将被视为 data-hash 属性的 HTML 编码内容,而不是看起来很奇怪的尝试HTML 属性。

关于html - Ruby JSON 多词字符串在 HTML 中呈现不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28443145/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com