在 Ruby 和 Ruby 中转义 HTML使用 JS 添加到 DOM
我正在尝试使用 JS 动态添加 div 的内容。后端是 Ruby on Rails。我遇到问题了。以下是视图文件中包含的内容:
var Product_sidebar_inner = "<%= CGI.escapeHTML(render(...somepartial...)).gsub(/\r/," ").gsub( /\n/," ") %>";
document.getElementById("left_sidebar_wrapper").innerHTML = unescape(product_sidebar_inner);
上面将 html 作为文本插入到 div#left_sidebar_wrapper 中。花了一些时间,但仍然无法完成这项工作。知道我做错了什么吗?
I'm trying to dynamically add contents of a div using JS. Back end is Ruby on Rails. I am having a problem. Here's what is included in the view file:
var product_sidebar_inner = "<%= CGI.escapeHTML(render(...some partial...)).gsub(/\r/," ").gsub(/\n/," ") %>";
document.getElementById("left_sidebar_wrapper").innerHTML = unescape(product_sidebar_inner);
The above inserts html as text to div#left_sidebar_wrapper. Spent some time on this but still can't make this work. Any idea what am I am doing wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
根据您对 macarthy 的评论,我认为您想要
CGI.escape
(或CGI.unescape
),这就是您用于 URL 编码的内容。您还可以使用URI。 escape
(或URI.unescape
),但你会厌倦必须一直传递unsafe
正则表达式来完成它你想要什么。另外,在 JavaScript 方面,您应该使用
encodeURI
或encodeURIComponent
为 < a href="https://developer.mozilla.org/en/Core_JavaScript_1.5_Guide/Functions#escape_and_unescape_Functions" rel="nofollow">escape
已被弃用,因为它存在非-ASCII 字符。Based on your comment to macarthy, I think you want
CGI.escape
(orCGI.unescape
), that's what you use for URL encoding. You can also useURI.escape
(orURI.unescape
) but you'll get tired of having to pass theunsafe
regex all the time to get it to do what you want.Also, on the JavaScript side, you should be using
encodeURI
orencodeURIComponent
asescape
is deprecated because it has problems with non-ASCII characters.认为你需要使用原始
THink you need to use raw