这个问题在这里已有答案:
我对python很新,对烧瓶的经验更少,我无法弄清楚这个问题。我有以下简单的网页,其中包含jQuery功能,当我双击文件并在浏览器中打开它时,它非常有用:
<!DOCTYPE html>
<html>
<head>
<script src="jquery-3.3.1.js"></script>
</head>
<body>
<script type="text/javascript">
$(document).ready(function() {
$("#updateBtn").on("click", function() {
text = "<h2>The div has been updated!</h2>";
$("#jQuery_div").html(text);
});
});
</script>
<div>
<h1>This is a non-jQuery div</h1>
</div>
<div id="jQuery_div">
<h2>This div should update with jQuery</h2>
</div>
<button id="updateBtn">update</button>
</body>
</html>
但是,当flask在localhost:5000上传递网页时,jQuery功能不再存在。我的python如下:
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def render():
return render_template("jquery_test.html")
if __name__ == "__main__":
app.run(port=5000, debug=True)
我的应用程序的文件树是:
/AJAX_practice
ajax_practice.py
/templates
jquery-3.3.1.js
jquery_test.html
当我无法使用“echo”按钮工作时,我试图关注this tutorial。在我的调试工作中,我已经慢慢消除并大大简化了程序到上面的代码,看看为什么我不能让我的jQuery通过烧瓶工作。我还是不知所措。我在IDLE中按F5运行烧瓶应用程序,在Python 2.7.13 Shell和终端(我用$ sudo idle
开始IDLE)中没有错误显示:
my ip - - [date and time] "GET / HTTP/1.1" 200 -
my ip - - [date and time] "GET /jquery-3.3.1.js HTTP/1.1" 404 -
从这个,我最好的猜测是烧瓶找不到jquery.3.3.1.js文件,虽然我已经尝试将它放在文件树中的任何地方而没有运气。我不能将脚本src用于https以获取jQuery依赖项,因为我的服务器最终将位于非Internet连接的LAN上。我是在正确的轨道上吗?如果是这样,烧瓶如何查找和/或导航jQuery依赖项?有人能指出一些可能有助于我对这个问题的基本理解的文档吗?
任何有关此事的帮助将不胜感激。
您正尝试从templates文件夹提供JavaScript文件。添加静态文件夹并使用它来提供静态内容。
在你的情况下创建一个像“static / js / jquery.min.js”这样的目录结构
然后像这样添加脚本引用
<script src="{{url_for('static', filename='js/jquery.min.js')}}"></script>
见:http://exploreflask.com/en/latest/static.html
如果您不想将其保存在“静态”文件夹中并使用其他本地目录,则可以使用send_from_directory
,如下例所示:https://stackoverflow.com/a/20648053/2118215
过去,这对Flask一直很有用:
<script src="{{ url_for('static', filename='jquery-3.3.1.js') }}"></script>
'static'是它所在文件夹的名称('static'文件夹位于我项目的根目录中)。您可以编辑它以适合您的首选结构和命名,因此如果您要保留jquery文件,请将“静态”更改为“模板”,但我建议将其保存在HTML模板的单独文件夹中,纯粹是保持项目组织良好的利益。
我相信jquery的路径应该是/templates/jquery-3.3.1.js
在我服务于jquery的烧瓶服务器上它有来自主目录的完整路径:/static/js/jquery.min.js