带计时器的 Jquery/Ajax 调用 [英] Jquery/Ajax call with timer

查看:39
本文介绍了带计时器的 Jquery/Ajax 调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 php 页面,可以从数据库中回显出行.我想每 30 秒通过 jquery/ajax 调用它.但我也希望能够随时调用页面,这样如果我通过表单添加记录,一旦表单提交,我希望页面通过调用 ajax 来立即更新结果.谁能指出我正确的方向或提供一些基本代码,以便我可以尝试解决这个问题?对 jquery/ajax 还是很陌生.

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.

推荐答案

如果你想在计时器上设置一些东西,你可以使用 JavaScript 的 setTimeoutsetInterval 方法:

If you want to set something on a timer, you can use JavaScript's setTimeout or setInterval methods:

setTimeout ( expression, timeout );
setInterval ( expression, interval );

其中expression 是一个函数,timeoutinterval 是以毫秒为单位的整数.setTimeout 运行一次计时器并运行一次 expression 而 setInterval 将在每次 interval 过去时运行 expression.

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.

所以在你的情况下它会像这样工作:

So in your case it would work something like this:

setInterval(function() {
    //call $.ajax here
}, 5000); //5 seconds

就 Ajax 而言,请参阅 jQuery 的 ajax() 方法.如果您运行间隔,则没有什么可以阻止您从代码中的其他地方调用相同的 ajax().

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.

如果您想要的是每隔 30 秒运行一次间隔,直到用户发起表单提交...然后在此之后创建一个新的间隔,那也是可能的:

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:

setInterval() 返回一个整数,它是间隔的 ID.

setInterval() returns an integer which is the ID of the interval.

var id = setInterval(function() {
    //call $.ajax here
}, 30000); // 30 seconds

如果将该 ID 存储在变量中,则可以调用 clearInterval(id) 来停止进程.

If you store that ID in a variable, you can then call clearInterval(id) which will stop the progression.

然后您可以在完成 ajax 表单提交后重新实例化 setInterval() 调用.

Then you can reinstantiate the setInterval() call after you've completed your ajax form submission.

这篇关于带计时器的 Jquery/Ajax 调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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