点击html页面的按钮后,可以开始不用刷新页面同步显示后端的结果。如同步下面count.py的结果count
import json, time, random
from threading import Thread
count=0
def foo():
global count
while True:
time.sleep(1)
count += 1
print(count)
t1 = Thread(target=foo)
t1.start()
可以完成同步上面程序的测试就采纳
大概如下
app.py
import json, time, random
from threading import Thread
from flask import *
count=0
def foo():
global count
while True:
time.sleep(1)
count += 1
print(count)
t1 = Thread(target=foo)
t1.start()
app = Flask(__name__)
@app.route('/',methods=['GET','POST'])
def index():
return render_template('index.html')
@app.route('/getcount',methods=['GET','POST'])
def getcount():
return str(count)
app.run()
templates\index.html
<meta charset="utf-8" />
<script src="https://g.csdnimg.cn/??lib/jquery/1.12.4/jquery.min.js"></script>
<input type="button"value="加载服务器数据" onclick="callserver(this)" />
<div id="dv"></div>
<script>
var timer
function callserver(el) {
var load = el.value == '加载服务器数据';
el.value = load ? '停止加载' : '加载服务器数据'
if (load) timer = setInterval(() => {
$('#dv').load('/getcount')
}, 2000);
else clearInterval(timer)
}
</script>
您好,我是有问必答小助手,您的问题已经有小伙伴帮您解答,感谢您对有问必答的支持与关注!