在 JavaScript 中使用 Rails 变量时转义引号?
我在尝试在 javascript 代码中使用 Rails 变量时遇到问题。
例如,我可能定义一个 link_to_remote,带有参数 <代码>:完成=> "alert('my_var');"
如果 my_var = "I'm testing."
,则 javascript 代码将因单引号过早关闭代码而中断。如果我尝试使用 escape_javascript(my_var)
将引号变成 \'
,它似乎并不能解决问题。
我注意到,当您尝试 alert('I\'m testing');
时会出现问题,但是如果您执行 alert('I\\'m testing')
代码>,它有效。由于 escape_javascript 只将 '
转换为 \'
,而不是 \\'
,有人对如何处理这个问题有建议吗?
谢谢! 埃里克
I am having problems when trying to use a rails variable within javascript code.
For example, I might define a link_to_remote, with parameter:complete => "alert('my_var');"
If my_var = "I'm testing."
, then the javascript code will break due to the single quote closing the code prematurely. If I try using escape_javascript(my_var)
so that the quote gets turned into \'
, it doesn't seem to fix the problem.
I've noticed that when you try alert('I\'m testing');
there's a problem, but if you do alert('I\\'m testing')
, it works. Since escape_javascript only turns '
into \'
, rather than \\'
, does somebody have a suggestion for how to handle this?
Thanks!
Eric
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
反斜杠也是 Ruby 字符串中的转义符!因此,字符串字面量:
表示字符串:
在 JavaScript 看到它之前,反斜杠已经消失了。当您在 Ruby 字符串文字内部编写 JavaScript 字符串文字时,您需要转义转义符
\\
,以获得真正的\
然后,在 JavaScript 中,将转义撇号。如果输入中包含反斜杠,
escape_javascript
会正确生成 JavaScript 的反斜杠。但同样,如果您正在编写字符串文字,则必须转义反斜杠才能获得真正的反斜杠:因此,这很好:
或者,您可以使用 JSON 编码器来创建包括周围引号的 JavaScript 字符串文字。
Backslash is also an escape in Ruby strings! So the string literal:
means the string:
the backslash is gone already before JavaScript gets a look at it. When you are writing a JavaScript string literal inside a Ruby string literal you need to escape the escape,
\\
, to get a real\
that will then, in JavaScript, escape the apostrophe.escape_javascript
correctly generates the backslash for JavaScript, if a backslash was included in its input. But again, if you're writing a string literal, you have to escape the backslash to get a real backslash:So, this is fine:
alternatively, you can use a JSON encoder to create the JavaScript string literal including the surrounding quotes.