javascript 使用 Rails 在视图中打印有效的、非转义的 JSON
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9691611/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Print valid, non-escaped JSON in a view with Rails
提问by D-Nice
I've tried everything. Every combination of the helpers raw
, html_safe
to_json
including some attempts with ::JSON.encode
and CGI.unescape
. The issue is that regardless of what I do, I can't print well-formed JSON in a view. It's always HTML escaped.
我什么都试过了。帮手的每一个组合raw
,html_safe
to_json
包括一些使用::JSON.encode
和 的尝试CGI.unescape
。问题是,无论我做什么,我都无法在视图中打印格式良好的 JSON。它总是 HTML 转义。
Here's the code in my view:
这是我认为的代码:
var campaignData<%= "=" + (raw @campaign.to_json) if @campaign %>;
var campaignData<%= "=" + (raw @campaign.to_json) if @campaign %>;
In my case, it's always the quotes that are escaped as ". I would just do a gsub on the quotes, but that is a terrible solution to what IMO ought to be a very simple, well documented use case.
在我的情况下,总是将引号转义为“。我只是在引号上做一个 gsub,但对于 IMO 应该是一个非常简单、有据可查的用例,这是一个糟糕的解决方案。
回答by Roman
The problem here is with the "=" string. As it's considered unsafe, it taints the other string.
这里的问题是“=”字符串。由于它被认为是不安全的,它会污染另一个字符串。
You can probably do either:
您可能可以执行以下任一操作:
raw("=" + @campaign.to_json)
or
或者
"= #{@campaign.to_json}".html_safe
which are roughly the same.
大致相同。
回答by Jesse Whitham
Since ActiveSupport 2.3.3 you have been able to do .as_json
自 ActiveSupport 2.3.3 以来,您已经能够做到 .as_json
回答by cutalion
Did you try escape_javascript
?
你试了escape_javascript
吗?
Here is an example from the *.haml file, which I just added to test my answer.
这是 *.haml 文件中的一个示例,我刚刚添加了该文件来测试我的答案。
:javascript
var foo=$.parseJSON("#{j @albums.to_json}")
Where j
is an short alias for escape_javascript
.
j
的短别名在哪里escape_javascript
。
回答by megas
Try this with utility method
用实用方法试试这个
var campaignData<%=h " =#{raw @campaign.to_json}" if @campaign %>;