Ale*_*lla 13 javascript django quotes jquery
在一个小论坛中,任何用户都可以保存帖子.有时这些帖子包括用引号("")包围的单词.当我尝试使用javascript处理这些字符串时,这会给我一个错误.
我写了一些使用django变量的jquery代码,如下所示:
new_text = "{{text|safe}}";
$("#text_p").text(new_text);
Run Code Online (Sandbox Code Playgroud)
如果我将其标记为"安全",那么javascript会给我一个语法错误:
the text "(error here)word between quotes" the user posted
Run Code Online (Sandbox Code Playgroud)
这是合乎逻辑的,因为javascript理解这样的引号:
new_text = "this is the text "word between quotes" the user posted"
Run Code Online (Sandbox Code Playgroud)
所以,如果我不将它标记为"安全"并让django转义文本,它不会给我一个错误,但文本看起来像这样:
the text "word between quotes" the user posted
Run Code Online (Sandbox Code Playgroud)
我不知道该怎么做,我想这可能不是简单的原因,如果我使用单引号来声明javascript变量,当用户发布带单引号的文本时,我会遇到同样的问题.如果我使用正则表达式替换双引号而不将文本标记为"text | safe",则其他标签将被转义,文本将充满"<br />"等.
我有一个可能有用的想法,但是很难看,可能不是最好的选择:在<p class = "hidden">标签中包含文本,然后使用jquery调用它.
所以,问题是,我该如何解决这个问题?,还有更好的方法吗?在此先感谢您的帮助.
编辑:我创建了一个Runnable来更好地解释它.
Art*_*rti 22
使用escapejs过滤器.例:
{{ string|escapejs }}
Run Code Online (Sandbox Code Playgroud)
好的,我找到了部分解决方案,希望它对将来的人有所帮助。这不是一个优雅的解决方案,因此,如果有人有更好的选择,将会受到欢迎。
我在 html 隐藏标记中包含了带有“引用”字样的文本。
python-django:
text_with_quotes = 'this is a text and a word between "quotes"'
html:
<p id = "new_text" class = "hidden"> {{text_with_quotes|safe}}</p>
js:
new_text = $("#new_text").text();
$("#text_p").text(new_text);
Run Code Online (Sandbox Code Playgroud)
有用。但使用 javascript 和/或 python 可能有更好的选择。