在Flask上运行时未添加外部JavaScript文件 [英] External JavaScript file is not getting added when running on Flask
问题描述
我有一个名为showMap.html
的HTML文件:
I have an HTML file named showMap.html
:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<title>Map</title>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false">
</script>
<script type="text/javascript" src="js/map.js"></script>
</head>
<body onload="showPosition()">
<div id="map_canvas" style="width:500px;height:500px;"></div>
</body>
</html>
另一个JavaScript文件map.js
放置在同一目录的js
文件夹中.
And another JavaScript file map.js
is placed in the js
folder of the same directory.
此代码在加载HTML文件时工作正常,但是在服务器中运行时却无法工作.
This code works fine when the HTML file is loaded, but this does not work when I run it in the server.
我使用Python的Flask框架进行后端编程,有趣的是,如果我在HTML文件中扩展JavaScript代码,则同样的东西也可以很好地工作.唯一的问题是外部文件.
I use Python's Flask framework for back-end programming and the funny thing is that the same thing will work well if I expand the JavaScript code inside the HTML file. The only problem is with the external file.
推荐答案
将map.js
文件作为静态资源:
-
将文件移动到软件包的
static/
子目录
在Jinja2模板中为其生成静态URL,如下所示:
generate a static URL for it in a Jinja2 template like so:
<script type="text/javascript"
src="{{ url_for('static', filename='map.js') }}"></script>
filename
参数采用相对路径;您可以使用需要的子目录.
The filename
parameter takes a relative path; you can use subdirectories was needed.
这篇关于在Flask上运行时未添加外部JavaScript文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!