我的多字字符串在DOM中沒有正確解釋。如何通過多字符串確保從服務器到HTML的JSON完整性?Ruby中的JSON多字符串在HTML中呈現錯誤
在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'添加到最後? – 2015-02-10 22:34:01
是的。它使它看起來更好一些,但實際上並沒有解決問題。 – steel 2015-02-10 22:36:18
通過查看Chrome檢查。 – steel 2015-02-10 23:14:34