JQuery&Timer ::从Web服务更新超链接的文本

我要弄清楚如何做是在远程服务器上执行web服务,以确定有多少消息可用于读取和填充带有消息计数的超链接的文本。 诀窍是我想要从定时器(例如每5分钟)发射一次。 这就是我一直在搞乱的事情

$.ajax( {type:'Get',url:'http://foobar.com/ws',success:function(messageCount) { $('a.message').text(messageCount + ' Messages'); } }) 

但不可否认,当谈到javascript / jquery中的计时器时,我完全无能为力。 任何帮助将不胜感激。

谢谢!

您需要使用setInterval()函数。 这将以指定的间隔运行定义的函数。 试试这个:

 $(function() { setInterval("getDataFromWS()", 300000) // 300,000 miliseconds is 5 minutes }); function getDataFromWS() { $.ajax({ type:'Get', url:'http://foobar.com/ws', success:function(messageCount) { $('a.message').text(messageCount + ' Messages'); } }) } 

如果你想定期这样做,你应该使用setInterval

 //create the timer (and save the unique id returned //so we can stop it later if needed, using clearTimer()) //This will fire every 300,000 millisecs (= 5 mins) //and call the updateMessageCount function var msgCounTimer = setInterval(updateMessageCount, 300000); function updateMessageCount() { $.ajax({ type:'GET', url:'http://foobar.com/ws', success:function(messageCount) { $('a.message').text(messageCount + ' Messages'); } }); } 

但是,如果你想使用setTimeout一次 – 你也可以定期使用setTimeout除了你每次都需要调用设置定时器。

我可以想到你可能想要使用setTimeout而不是setInterval的一种情况是,你在函数中调用的函数超时(在我下面的例子中是updateMessageCount )花费的时间超过了会导致下一次超时(当使用setInterval )似乎是瞬时的,因为定时器将每n秒触发一次,而不管前一次超时调用的函数是否仍在执行。 相反,如果你想确保连续调用超时处理程序之间有n毫秒(而不是每隔n毫秒调用一次超时处理程序),你应该使用setTimeout并在每次完成重量时设置它处理。

注意我看到你在示例中使用的是绝对URL,所以我想我会指出这一点,以防你不熟悉它 – 注意同源策略限制你的JavaScript向其他域请求而不是它的起源。

你需要在Javascript中查看setTimeout函数

例如var t=setTimeout("yourfunction()",10000);