转义字符串 - 在 Javascript 中输出 rails 字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18854749/
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
Escape String - Output rails string in Javascript
提问by cclerv
I'm trying to assign a string value to a javascript object in my .erb file like so:
我正在尝试将字符串值分配给 .erb 文件中的 javascript 对象,如下所示:
var data = {
'name': '<%= @product.name %>',
...
};
The problem is, if the value of nameis Tom's small ears,
问题是,如果值name是Tom's small ears,
the output of data.namewould be Tom's small ears.
的输出data.name将是Tom's small ears。
Is there a way to escape special characters?
有没有办法转义特殊字符?
I tried doing 'name': '<%= raw @product.name %>'but Uncaught SyntaxError: Unexpected identifiergets output into the console.
我尝试这样做,'name': '<%= raw @product.name %>'但Uncaught SyntaxError: Unexpected identifier输出到控制台。
Doing <%= escape_javascript @product.name %>outputs Tom\'s small ears
做<%= escape_javascript @product.name %>输出Tom\'s small ears
Edit@Stefan's comment under MrYoshiji'sanswer worked for me.
在MrYoshiji's回答下编辑@Stefan 的评论对我有用。
回答by MrYoshiji
You can use escape_javascript()to accomplish that:
你可以用它escape_javascript()来完成:
var data = {
'name': "<%== escape_javascript @product.name %>",
#...
};
链接:http: //api.rubyonrails.org/classes/ActionView/Helpers/JavaScriptHelper.html#method-i-escape_javascript
The alias of this method is j:
该方法的别名是j:
var data = {
'name': "<%== j @product.name %>"
}
回答by Hooopo
var data = {
'name': '<%=j @product.name.html_safe %>',
...
};

