简体   繁体   English

如何在服务器上的Python中单击引用以在客户端上的Javascript中使用

[英]How to Escape Single Quotes in Python on Server to be used in Javascript on Client

>>> sample = "hello'world"
>>> print sample
hello'world
>>> print sample.replace("'","\'")
hello'world

In my web app I need to store my python string with all single quotes escaped for manipulation later in the client browsers javascript. 在我的网络应用程序中,我需要存储我的python字符串,所有单引号都被转义,以便稍后在客户端浏览器javascript中进行操作。 Trouble is python uses the same backslash escape notation so the replace operation as detailed above has no effect. 麻烦是python使用相同的反斜杠转义表示法,因此上面详述的替换操作无效。

Hopefully there is a simple workaround? 希望有一个简单的解决方法?

As a general solution for passing data from Python to Javascript, consider serializing it with the json library (part of the standard library in Python 2.6+). 作为将数据从Python传递到Javascript的一般解决方案,请考虑使用json库(Python 2.6+中的标准库的一部分)对其进行序列化。

>>> sample = "hello'world"
>>> import json
>>> print json.dumps(sample)
"hello\'world"

Use: 使用:

sample.replace("'", r"\'")

or 要么

sample.replace("'", "\\'")

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

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