AJAX Flask POST向所有客户端发送相同的数据



我成功地获得了倒计时时间数据,但是当多个客户端连接到服务器时,每个人的数据看起来都不一样。(计时器失效,开始每秒跳跃多次)

我如何确保不断更新的数据以相同的方式发送到所有客户端?

My Flask route.

@app.route("/countdown",methods=["POST"])
def countdown():
countdown_second = int(get_db()["countdown"]) # get countdown second from db
delta_t = str(datetime.timedelta(seconds=countdown_second))
change_countdown_time(countdown_second-1) #write new countdown second to db

return jsonify(delta_t),200

My AJAX call.

$('document').ready(function () {
setInterval(function () {GET_countdown()}, 1000);
});

function GET_countdown() {
$.ajax({
url: "/countdown",
method: "POST",
success: function(response) {
$("#countdown").html(response);
},
error: function(error) {
console.log(error);
},
})
}

你的倒计时依赖于客户端(你的javascript)每秒钟的倒计时。问题是,对于每个客户机,这将每秒发生一次。因此,它只适用于一个客户端,而不是多个客户端。

一个更好的方法是让你的服务器负责倒计时。如何做到这一点,可以在数据库中存储一个对应于0的datetime。然后,对于每个POST,它根据当前时间计算秒数。

@app.route("/countdown")
def countdown():
# You might have to change things with your db to get this to work, but here is the concept.
countdown_datetime = get_db()["countdown"] # get datetime when countdown is 0
delta_t = (datetime.now() - countdown_datetime).total_seconds()

return jsonify(delta_t),200

也不是,我将它从POST更改为GET,因为这个端点不再更改值,它只报告它们。

最新更新