如何定期更新网页上的服务器端值? [英] How to periodically update server-side value on webpage?

查看:34
本文介绍了如何定期更新网页上的服务器端值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个存储在 MySQL 数据库中的时间戳,我想定期(比如每秒)更新当前时间和存储在数据库中的时间戳值之间的差异(当然无需重新加载页面)以显示某些内容就像一个 5 分钟倒数计时器.马上.我正在考虑使用 setTimeout 定期触发获取此值的 AJAX 请求.这是最好的方法吗?相反,我应该只运行一个客户端计时器,然后每隔一分钟左右将它与服务器端时间戳同步吗?

I have a timestamp stored in a MySQL database, and I want to periodically (say every second), update the difference between the current time and the timestamp value stored on the database (of course without reloading the page) to show something like a 5 minute count-down timer. Right now. I'm thinking use setTimeout to periodically fire an AJAX request that gets this value. Is this the best approach? Instead, should I just run a client-side timer, and then sync it with the server-side timestamp every minute or so?

注意:这个计时器负责我网站上的一个重要功能,所以它应该相当准确.

Note: This timer is responsible for an important function on my website, so it should be reasonably accurate.

我不需要 cron 工作,我只需要一个倒数计时器,它可以在网页上更新,例如从 5:00 到 4:59 到 4:58...等等,自动地.如果您熟悉 Megaupload 关闭前的那个,我需要类似的东西.

I don't need a cron job, I just need a countdown timer that updates on a webpage like from 5:00 to 4:59 to 4:58... etc, automatically. If you're familiar with the one Megaupload had before it was shutdown, I need something similar.

推荐答案

由于 Javascript 工作方式的性质,几乎不可能实现精确的计时器(有关更多详细信息,请参见此处).

Because of the nature of the way Javascript works, exact timers are next to impossible to achieve (see this for more details).

但是,您可以做一些非常接近它的事情,我建议您要做的是在客户端(用户可篡改但资源消耗最小)并且更重要的是使用服务器端验证以防止用户篡改它.所以你一开始就在数据库中设置了一个值,上面写着在 x 时间之前不接受提交",然后客户端就可以处理计时器了.

However, you can do something very close to it, and I'd suggest that what you want to do is do it all client-side (which is user-tamperable but minimal resource consumption) and more importantly use server side validation to prevent the user being able to tamper with it. So you set a value in the database at the beginning that says "don't accept the submit before x time" and then the client can handle the timer.

这是一个非常小的例子,说明如何做到这一点

这篇关于如何定期更新网页上的服务器端值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆