简体   繁体   English

使用Javascript + Rails转义报价

[英]Escaping Quotes with Javascript + Rails

In my rails app, I'm adding text dynamically to the page using something like this 在我的Rails应用中,我正在使用类似以下内容的方式向页面动态添加文本

$('.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. 问题是有时ruby变量“ description”包含单引号(例如,它可能包含单词“ I'm”),这在页面尝试呈现文本时导致错误。

What's the best way to avoid this problem by escaping quotes in description ? 通过在描述中转义引号来避免此问题的最佳方法是什么?

Checkout Rails' JavaScript Helper , in particular escape_javascript(javascript) Checkout Rails的JavaScript Helper ,尤其是escape_javascript(javascript)

Escapes carriage returns and single and double quotes for JavaScript segments. 转义JavaScript段的回车和单引号和双引号。

Also available through the alias j(). 也可以通过别名j()获得。 This is particularly helpful in JavaScript responses, like: 这在JavaScript响应中特别有用,例如:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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