在 Flask 上运行时未添加外部 JavaScript 文件 [英] External JavaScript file is not getting added when running on Flask

查看:18
本文介绍了在 Flask 上运行时未添加外部 JavaScript 文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为 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 框架进行后端编程,有趣的是,如果我将 JavaScript 代码扩展到 HTML 文件中,同样的事情也能很好地工作.唯一的问题是外部文件.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆