我在 python 中有一段代码,我试图将一些图像的动态路径发送到 javascript,但由于某种原因,“\”(分隔符)被删除。我试图通过一次发送一张图像来实现这一目标。 我使用tornado作为python服务器,并且有带有html的javascript代码。
server.py
import tornado.ioloop
import tornado.web
import time
import os
class one(tornado.web.RequestHandler):
def get(self):
self.write('Hello')
class Article(tornado.web.RequestHandler):
def get(self):
dir_path = os.path.dirname(os.path.realpath(__file__))
dir_path=os.path.join(dir_path, 'images')
file='2000px-Python-logo-notext.svg_.jpg'
file=os.path.join(dir_path, file)
var1 = 'Orignal_Appp'
self.render('template.html', var=var1, file1=file)
application = tornado.web.Application([
(r"/", one),
(r"/articles", Article),
],debug=True)
if __name__ == "__main__":
application.listen(8888)
tornado.ioloop.IOLoop.instance().start()
template.html
<html>
<title>
</title>
<body>
<br>
<h1 align="center"> </h1>
<br>
<div id='div2' align="center">
<h4>{{var}}</h4>
</div>
<div id='div1' align="center" >
<p><img id="dynamicImg" src="" style="width:300px;height:300px;"/></p>
</div>
</body>
<script>
var N = "{{ file1 }}";
var img = document.getElementById('dynamicImg');
img.src = N
document.write(N)
</script>
</html>
“document.write(N)”输出的图像路径:
D:namanimagesimages0px-Python-logo-notext.svg_.jpg
应该是这样的:
D:\naman\images\images\2000px-Python-logo-notext.svg_.jpg
此外,如果在 server.py 中我将“images/2000px-Python-logo-notext.svg_.jpg”作为硬编码路径值而不是变量传递,则它可以正常工作。所以,我的理解是 javascript 正在解析路径并删除“\”反斜杠。我很确定,这是因为反斜杠字符,我认为这不会发生在 flask 中。所以它可能与 Tornado 有关,尽管我不确定。这也可能有一个非常常见/通用的解决方案。让我知道。
硬编码:
self.render('template.html', var=var1, file1='images/2000px-Python-logo-notext.svg_.jpg')
变量:
self.render('template.html', var=var1, file1=file)
我使用的是 windows 10、Python 3.7.3、tornado==5.1.1,但我也想了解其他平台(linux)。 另外,这可能是一个很常见的问题,我可能忽略了。我不知道。 我四处寻找这个场景以及其他场景,但这个问题可能是重复的,在这种情况下,请引导我找到问题的解决方案。如果有人知道任何 javascript 函数可以解决这个问题 任何信息、帮助将不胜感激。
提前致谢!
最佳答案
var N = "{{ file1 }}";
变成 var N = "D:\naman\images\images\2000px-Python-logo-notext.svg_. jpg";
和 backslash is a special character在 JavaScript 字符串中。
您需要转义此字符串以便在 JavaScript 字符串文字中使用。 Tornado 的默认转义行为适用于 HTML(其中尖括号等字符是特殊的,但反斜杠不是)。最简单的方法是使用 json_encode 函数(它将把 python 字符串转换为 javascript 字符串):
var N = {% raw json_encode(file1) %};
请注意,这里没有引号 - json_encode
负责添加它们。
转义很棘手 - 您应该确保使用包含特殊字符(包括反斜杠、尖括号、空格、与号和加号)的路径来测试您的应用程序。
关于javascript - 解析从 python(tornado) 到 javascript 的路径变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57393258/