简体   繁体   中英

Escaping Quotes with Javascript + Rails

In my rails app, I'm adding text dynamically to the page using something like this

$('.container').append('<div class="test"><%=description%></div>')

The issue is that sometimes the ruby variable "description" contains single quotes (for example, it might container the word "I'm"), which leads to errors when the page tries to render the text.

What's the best way to avoid this problem by escaping quotes in description ?

Checkout Rails' JavaScript Helper , in particular escape_javascript(javascript)

Escapes carriage returns and single and double quotes for JavaScript segments.

Also available through the alias j(). This is particularly helpful in JavaScript responses, like:

$('some_element').replaceWith('<%=j render 'some/element_template' %>');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM