大概如下
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>