rmd*_*_po 6 html javascript python flask jsonify
我正在使用 Flask 构建一个游戏,其中每一轮都有一个完成该轮的倒计时。我希望时间值每秒减少 1 并且在不重新加载页面的情况下进行更新。倒计时本身使用 time.sleep 等待 1 秒,然后将生成器的下一个值设置为全局变量,该变量通过 jsonify 传递到我的 HTML。但是它不起作用。任何帮助,将不胜感激!
Python:
def countdownGen(t):
return (t-i for i in range(t))
def countdown(t):
gen = countdownGen(t)
while t > 0:
try:
globaltimer = next(gen)
time.sleep(1)
except StopIteration:
globaltimer = 0
@app.route('/_timer', methods=['GET'])
def timer():
global globaltimer
globaltimer = 60
countdown(globaltimer)
return jsonify(result=globaltimer)
Run Code Online (Sandbox Code Playgroud)
HTML / JS:
<script type="text/javascript">
var intervalID = setInterval(update_values,1000);
$SCRIPT_ROOT = {{request.script_root|tojson|safe}};
function update_values() {
$.getJSON($SCRIPT_ROOT + '/_timer',
function(data) {
$('#result').text(data.result);
});
};
</script>
<body onload="update_values();">
<span id="result">?</span>
<script>
document.getElementById("result").innerHTML;
</script>
</body>
Run Code Online (Sandbox Code Playgroud)
你可以这样做:
from flask import Flask, render_template, jsonify
app = Flask(__name__)
class Timer:
def __init__(self, current_time):
self.current_time = current_time
def decrement(self):
if self.current_time > 0:
self.current_time = self.current_time - 1
return self.current_time
t = Timer(current_time=60)
@app.route("/", methods=["GET"])
def index():
return render_template("index.html")
@app.route("/_timer", methods=["GET", "POST"])
def timer():
new_time = t.decrement()
return jsonify({"result": new_time})
if __name__ == "__main__":
app.run()
Run Code Online (Sandbox Code Playgroud)
和这个:
<body>
<span id="result"></span>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="{{ url_for('static', filename='jquery.js') }}">\x3C/script>')</script>
<script type="text/javascript">
const root_url = {{request.root_url|tojson|safe}};
const intervalID = setInterval(update_values, 1000);
function update_values() {
$.getJSON(
root_url + "_timer",
data => {
$("#result").text(data.result);
if (data.result == 0) {
clearInterval(intervalID);
}
}
)
}
</script>
</body>
Run Code Online (Sandbox Code Playgroud)
当我登录时,request.script_root我收到一个空字符串,导致请求失败,因此这也可能是您的问题。我用request.root_url的是。request.root_url确实有一个尾部斜杠,因此当您尝试用它调用端点时需要注意这一点。
这里的想法是创建一个类,可以在该类的实例中传递初始时间,该初始时间可以递减并返回。
在您的代码中,您同时使用setInterval(update_values, 1000)和time.sleep(1)。我删除了该time.sleep(1)调用,因为我们已经_timer每秒只调用端点一次,所以我们不需要再等待一秒钟。
如果时间超过,我只会减少时间0。在模板中,if data.result(即从 Flask 接收到的时间)是0我们不再递减并清除间隔。
另请注意,由于我们根据刷新之类的内容来减少时间,setInterval因此不会重置计时器。这可能是理想的行为,但无论如何都要记住。
| 归档时间: |
|
| 查看次数: |
4208 次 |
| 最近记录: |