转义字符串-Java中的输出rails字符串 [英] Escape String - Output rails string in Javascript
本文介绍了转义字符串-Java中的输出rails字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试为.erb文件中的javascript对象分配一个字符串值,如下所示:
I'm trying to assign a string value to a javascript object in my .erb file like so:
var data = {
'name': '<%= @product.name %>',
...
};
问题是,如果 name的值
是汤姆的小耳朵
,
data.name $ c的输出$ c>会是
Tom&#x27;的小耳朵
。
有没有一种方法可以逃脱特殊字符?
Is there a way to escape special characters?
我尝试做'name':'<%= raw @ product.name%>'
但是语法错误:意外的标识符
输出到控制台。
I tried doing 'name': '<%= raw @product.name %>'
but Uncaught SyntaxError: Unexpected identifier
gets output into the console.
执行<% = escape_javascript @ product.name%>
输出 Tom\&#x27; s小耳朵
编辑
@Stefan在 MrYoshiji的
答案下的评论对我有用。
Edit
@Stefan's comment under MrYoshiji's
answer worked for me.
推荐答案
您可以使用 escape_javascript()
完成此操作:
You can use escape_javascript()
to accomplish that:
var data = {
'name': "<%== escape_javascript @product.name %>",
#...
};
此方法的别名为 j
:
var data = {
'name': "<%== j @product.name %>"
}
这篇关于转义字符串-Java中的输出rails字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文