我正在尝试使用 Flask 获取一个 python 脚本来定期将当前时间推送到 HTML 页面。 (这不是我的最终目标,这只是我试图解决的问题的一个非常简单的版本。)我似乎无法让 JavaScript 不断地从 Python 脚本请求更新的数据。我究竟做错了什么?该代码很大程度上是根据之前发布的类似问题拼凑而成的,但我仍然不知道如何让它工作。
Python 代码:
from flask import Flask, render_template
from datetime import datetime
app = Flask(__name__)
@app.route("/")
def template_test():
return render_template('template.html')
@app.route('/get_time', methods= ['GET', 'POST'])
def stuff():
result = datetime.utcnow()
return jsonify(result=result)
if __name__ == '__main__':
app.run(debug=True)
HTML:
<html>
<body>
<p id="result">Time goes here</p>
<script>
setInterval(
function()
{
$.getJSON(
$SCRIPT_ROOT + '/get_time',
{},
function(data)
{
$("#result").text(data.result);
});
},
500);
</script>
</body>
</html>
最佳答案
这是您的完整 HTML 吗?我问这个问题是因为虽然你的脚本对我来说看起来不错,但你正在使用 jQuery 命令,但似乎没有导入 jQuery 库本身。
添加<head><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script></head>
在你的<html>
之间和<body>
文件顶部的标签应该会有所帮助。
此外,在如此简单的情况下,它并不是真正需要的,但在使用 jQuery 将脚本包含在 $(document).ready(function() { your_script_here });
中时,这是一个很好的做法。 - 一旦文档完全加载,这将执行它,因此您不必冒险尝试对更复杂的文档中尚未加载或渲染的元素执行操作。
关于javascript - 使用 Flask 从 python 脚本定期更新 HTML 中的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40733794/