我在python中有一段代码,尝试将少数图像的动态路径发送到javascript,但由于某些原因,“\”(分隔符)被删除。我试图通过一次发送一个图像来实现这一点。 我使用tornado作为python服务器,并使用带有html的javascript代码。你知道吗
服务器.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()
模板.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>
“的图像路径的输出”文档.写入(N) “:”
D:namanimagesimages0px-Python-logo-notext.svg_.jpg
应该是这样的:
D:\naman\images\images\2000px-Python-logo-notext.svg_.jpg
如果在服务器.pyI pass'images/2000px Python徽标-notext.svg文件_.jpg'作为硬编码的路径值而不是变量,它可以正常工作。所以,我的理解是javascript正在解析路径并删除“\”反斜杠。我敢肯定,这是因为反斜杠字符,我认为这不会发生在烧瓶。所以它可能和龙卷风有关,尽管我不确定。这还不如有一个非常通用的解决方案。让我知道。你知道吗
硬编码:
self.render('template.html', var=var1, file1='images/2000px-Python-logo-notext.svg_.jpg')
变量:
self.render('template.html', var=var1, file1=file)
我使用的是windows10,python3.7.3,tornado==5.1.1,但我也想了解其他平台(linux)。 此外,这可能是一个非常常见的问题,我可能忽略了。我不确定。 我环顾了一下这个场景以及其他场景,但是可能这个问题是重复的,在这种情况下,请直接告诉我这个问题的解决方案。如果有人知道任何javascript函数可以解决这个问题 如有任何信息,请帮忙。你知道吗
提前谢谢!你知道吗
var N = "{{ file1 }}";
在javascript字符串中变成var N = "D:\naman\images\images\2000px-Python-logo-notext.svg_.jpg";
和backslash is a special character。你知道吗您需要转义这个字符串,以便在javascript字符串文本中使用。Tornado的默认转义行为适用于HTML(其中尖括号之类的字符是特殊的,但反斜杠不是)。最简单的方法是使用
json_encode
函数(这将把python字符串转换成javascript字符串):注意这里没有引号-
json_encode
负责添加它们。你知道吗转义是很棘手的-你应该确保测试你的应用程序的路径包含特殊字符,包括反斜杠,尖括号,空格,符号和加号。你知道吗
相关问题 更多 >
编程相关推荐