[英]Escaping html / javascript: Appending content of db field into DOM with jQuery
I want to do the following within rails. 我想在rails中执行以下操作。 In a textfield of my db, there is the following html / javascript:
在我的数据库的文本字段中,有以下html / javascript:
<script type="text/javascript">
document.write('<div id="test"></div>');
</script>
I want to append the contents of this field into the head-tag of the DOM, so the inserted js will be executed. 我想将此字段的内容附加到DOM的头部标签中,因此将执行插入的js。
In my rails erb-view, I have the following: 在我的erb视图中,我具有以下内容:
<script type="text/javascript">
var code = "<%= @ticket.code %>"; // Content of codesnippet above
$('head').append(code);
</script>
However I get some the following rendered output of the view: 但是我得到了以下视图的渲染输出:
var code = "<script type="text/javascript">
document.write('<div id="test"></div>');
</script>";
Error message: unterminated string literal 错误消息: 未终止的字符串文字
I tried to gsub linebreaks and other ways of escaping, but I've got no clue, what actually is the best way to escape it. 我尝试过换行符和其他逃逸方式,但我一无所知,实际上逃脱它的最佳方法是什么。 How can I get it correclty escaped and inserted into the DOM?
我如何才能正确删除并插入DOM?
Thanks for your help! 谢谢你的帮助!
I believe rails 3 comes with JQuery so why not just use: 我相信JQuery附带了Rails 3,所以为什么不直接使用:
$(document).onload(function()
{
document.write('<div id="test"></div>');
});
and I believe on var code you should do the following: 我相信在var代码上,您应该执行以下操作:
var code = "<%= escape_javascript(@ticket.code.html_safe) %>"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.