javascript - Python/Flask 中基于时间的 Jinja 元素自动重新加载,无需刷新页面

标签 javascript jquery python html ajax

所以我一直在尝试让它与 Ajax 和 JQuery 一起使用,但我似乎无法得到它。我对这两个都是新手。抱歉,如果这很微不足道,我已经搜索并研究了以前的答案一段时间了。

信息:

我的页面 html 中有一个 Jinja 标签,我想每秒更新一次:

 <pre id="#system_info_tag">{{ system_info_text }}</pre>

该信息最初(并成功)从我的主 python 脚本填充到一个名为 get_system_info() 的较大函数中:

@app.route('/')
def root():
    return render_template('system_info.html', system_info_text=get_system_info())

我希望元素每秒自动重新加载一次,所以我尝试使用 JS 来执行此操作,如下所示(我认为这会重新运行我的 python 函数,因为重新加载页面会更新它):

function() {
    setInterval(function() {
        $("#system_info_tag").load(location.href + " #system_info_tag");
    }, 1000);
});

它被加载到我的 html 文件中:

<script src="static/js/update_refresh.js"></script>

页面加载正确,信息正确,但元素不会自动重新加载。任何帮助将不胜感激。

最佳答案

ma​​in.py

@app.route('/')
def root():
    return render_template('system_info.html', system_info_text=get_system_info())

@app.route("/sys_info.json")
def system_info(): # you need an endpoint on the server that returns your info...
    return get_system_info()

templates/system_info.html

<script src="https://code.jquery.com/jquery-3.2.1.js"></script>
<div id="content">{{ system_info }}</div> {# this is the original system_info passed in from the root view #}

<script>
setInterval(function(){ // load the data from your endpoint into the div
    $("#content").load("/sys_info.json")
},1000)
</script>

我想还是这样

关于javascript - Python/Flask 中基于时间的 Jinja 元素自动重新加载,无需刷新页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46719648/

相关文章:

javascript - jQuery:只显示/隐藏而不是滑入/滑出

javascript - AngularJS - 根本不触发/获取 Http 请求

javascript正则表达式提取包含特定单词的所有句子2次

javascript - Jquery 菜单,单击时可切换类以一次展开一个列表级别

python - 在 Dreamhost 上使用 Python 接收 AJAX 数据

python - 使用 linux 删除 python 安装文件后如何向管理员发送电子邮件警报?

python - 在 Python 中查询数据库并存储到数据结构中

JavaScript 获取当前应用于元素的样式列表

javascript - 对象不支持 ScriptResource.axd 中的此属性或方法

javascript - 无需在 AngularJS 中重新初始化 Controller 即可更改包含的页面和 URL