Javascript 带计时器的 Jquery/Ajax 调用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4542863/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Jquery/Ajax call with timer
提问by John
I have a php page that echos out rows from a database. I want to call it via jquery/ajax every 30 seconds. But I also want to be able to call the page at any time so that if I add a record via the form, once the form submits I want the page via called to ajax to update the results right away. Can anyone point me in the right direction or provide some base code so I can try to figure this out? Still very new to jquery/ajax.
我有一个 php 页面,可以从数据库中回显出行。我想每 30 秒通过 jquery/ajax 调用它。但我也希望能够随时调用页面,以便如果我通过表单添加记录,一旦表单提交,我希望页面通过调用 ajax 来立即更新结果。谁能指出我正确的方向或提供一些基本代码,以便我可以尝试解决这个问题?对 jquery/ajax 来说还是很新的。
回答by treeface
If you want to set something on a timer, you can use JavaScript's setTimeout
or setInterval
methods:
如果你想在计时器上设置一些东西,你可以使用 JavaScript 的setTimeout
或setInterval
方法:
setTimeout ( expression, timeout );
setInterval ( expression, interval );
Where expression
is a function and timeout
and interval
are integers in milliseconds. setTimeout
runs the timer once and runs the expression
once whereas setInterval will run the expression
every time the interval
passes.
其中expression
是一个函数,timeout
和interval
是以毫秒为单位的整数。setTimeout
运行计时器一次并运行expression
一次,而 setInterval 将在expression
每次interval
通过时运行。
So in your case it would work something like this:
所以在你的情况下,它会像这样工作:
setInterval(function() {
//call $.ajax here
}, 5000); //5 seconds
As far as the Ajax goes, see jQuery's ajax()
method. If you run an interval, there is nothing stopping you from calling the same ajax()
from other places in your code.
就 Ajax 而言,请参阅 jQuery 的ajax()
方法。如果您运行一个时间间隔,则没有什么可以阻止您从ajax()
代码中的其他地方调用相同的内容。
If what you want is for an interval to run every 30 seconds until a user initiates a form submission...and then create a new interval after that, that is also possible:
如果您想要的是每隔 30 秒运行一次间隔,直到用户启动表单提交......然后在此之后创建一个新的间隔,这也是可能的:
setInterval()
returns an integer which is the ID of the interval.
setInterval()
返回一个整数,它是间隔的 ID。
var id = setInterval(function() {
//call $.ajax here
}, 30000); // 30 seconds
If you store that ID in a variable, you can then call clearInterval(id)
which will stop the progression.
如果将该 ID 存储在变量中,则可以调用clearInterval(id)
它来停止进程。
Then you can reinstantiate the setInterval()
call after you've completed your ajax form submission.
然后,您可以setInterval()
在完成 ajax 表单提交后重新实例化调用。