【发布时间】:2021-07-16 05:21:31
【问题描述】:
我正在成功运行以下脚本:它每 3 秒更新一次文本
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script>
$(function() {
window.setInterval(function() {
loadNewText()
}, 3000)
function loadNewText() {
$.ajax({
url: "/update_report",
type: "POST",
dataType: "json",
success: function(data) {
$(report).replaceWith(data)
}
});
}
});
</script>
我想将 HTML 中的函数更改为仅在 Python 代码中的某些变量发生更改时才运行“loadNewText()”!
我已将变量放入 python 路由中:
@app.route('/console-output')
def console_output():
fileHandle = open("console_output.txt", "r")
lineList = fileHandle.readlines()
fileHandle.close()
last= lineList[len(lineList)-1]
with open('console_output.txt', 'r') as r:
co =r.read()
return render_template("console-output.html",console_output_msg=console_output_msg, last=last, co=co)
并在 HTML 中编写以下代码:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script>
$(function() {
if (last != console_output_msg) {
loadNewText();
}
function loadNewText() {
$.ajax({
url: "/update_text",
type: "POST",
dataType: "json",
success: function(data) {
$(new_text).replaceWith(data)
}
});
}
});
</script>
此方法无效!我对 Javascript 没有丰富的经验!我不知道我是否没有以正确的方式调用变量(最后一个,console_output_msg)或者我的函数无效!
如果有任何方法可以纠正它或任何其他建议在 python 代码发生更改时调用“loadNewText()”!
谢谢!
【问题讨论】:
-
您无法在客户端访问服务器变量。而且你已经摆脱了
setInterval,所以它不会重复运行。 -
你想要的在逻辑上是不可能的。在您进行 AJAX 调用之前,Python 代码不会运行。所以变量在你调用它之前不会得到一个值,只有这样你才能测试它是否从之前的调用中改变了。
-
@Barmar 是否可以使用
setInterval来比较来自 Python 代码的两个变量并在特定条件下运行函数? -
您需要进行 AJAX 调用才能将 Python 中的变量导入 JS。
-
@Barmar 您能否提供一个示例或链接,以便我可以找到有关该解决方案的更多信息?
标签: javascript python html jquery flask