如何在 Javascript 中将按钮点击率限制为每分钟一次
我有一个基于 PHP 的 Web 应用程序,用于监视进程的状态并显示具有该状态的页面。用户可以单击页面上的按钮来更新状态。但是,我的服务器上的处理负载足够重,因此不希望过于频繁地更新状态。因此,我想要一种方法来限制某人每分钟点击“提交”按钮一次(这会刷新页面上显示的状态)。例如,如果有人在 12:00:00 单击该按钮,则在 12:01:00 之前他们应该无法再次单击该按钮。
单击按钮后,我可能想禁用该按钮并在一分钟过去后重新启用它 - 这是我的首选解决方案。
非常感谢。
I have a PHP-based web application that monitors the status of a process and displays a page with that status. Users can click a button on the page to update the status. However, the processing load on my server is heavy enough that updating the status too frequently is undesirable. So I want a way to limit someone to one click per minute on the Submit button (which refreshes the status displayed on the page). For example, if someone clicks the button at 12:00:00, they should not be able to click it again until 12:01:00.
After a click on the button, I would like to perhaps disable the button and re-enable it after one minute has passed - that's my preferred solution.
Thank you very much.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
wtf...人们对 jQuery 上瘾了。
wtf... people is jQuery addicted.
只是一个建议,但如果您打算通过使用客户端计时器(setTimeout)编写代码来限制提交按钮的速率,那么为什么不直接删除更新按钮,然后将页面按照您预先定义的时间间隔自动更新?
下面是 jQuery 中的一些示例代码(因为 jQuery 提供了一些出色的跨浏览器 AJAX 支持)
Just a suggestion, but if you're going to go through the trouble to write the code to rate-limit the submit button by using a client-side timer (setTimeout), why not just remove the update button all together, and make the page auto-update at your pre-defined interval?
Here's some sample code in jQuery (since jQuery offers some great cross-browser AJAX support)
要执行此纯 JavaScript,您可以简单地捕获单击事件,禁用按钮并在超时后再次启用它,下面的代码使用 jQuery 并假设您的按钮有一个 id 'button' ( 或者如果是输入:点击!)
你说进度相当重,注意即使尽管人们不能每分钟按下按钮一次以上(如果他们启用了 javascript),他们仍然可以禁用 javascript 并按他们想要的次数按按钮,或者根据需要多次直接调用 url。
编辑向脚本添加了完整的 HTML
To do this pure javascript, you can simply capture the click event, disable the button and enable it again after a timeout, the below code is using jQuery and assuming your button has an id 'button' (<button id="button">Click!</button> or if it is an input: <input type='button' id="button">Click!</input>)
You say the progress is quite heavy, note that even though people can not press the button more then once a minute (if they have javascript enabled that is) they can still disable javascript and press the button as much as they want, or call the url directly as many times as they feel like.
EDIT Added full HTML to script
使用setTimeout。
Use setTimeout.
使用 underscore.js 这很简单:
using underscore.js this is as easy as: