Thursday, May 9, 2024
37
rated 0 times [  43] [ 6]  / answers: 1 / hits: 19344  / 15 Years ago, sun, january 31, 2010, 12:00:00

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


More From » ruby-on-rails

 Answers
4

when you try alert('I'm testing'); there's a problem




Backslash is also an escape in Ruby strings! So the string literal:



alert('I'm testing');


means the string:



alert('I'm testing');


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:



escape_javascript(b)     -> this is a backspace character!
escape_javascript(\b) -> this is backslash-then-letter-b;
escaped for JavaScript literal to double-backslash-then-b.


So, this is fine:



'+escape_javascript(myvar)+'


alternatively, you can use a JSON encoder to create the JavaScript string literal including the surrounding quotes.


[#97703] Thursday, January 28, 2010, 15 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
mireyag

Total Points: 73
Total Questions: 107
Total Answers: 85

Location: Ukraine
Member since Sun, Dec 13, 2020
3 Years ago
mireyag questions
Sun, Aug 15, 21, 00:00, 3 Years ago
Wed, Dec 16, 20, 00:00, 3 Years ago
Tue, Sep 1, 20, 00:00, 4 Years ago
Sun, Jul 5, 20, 00:00, 4 Years ago
;