jQuery Ajax 请求每 30 秒一次
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4450579/
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 request every 30 seconds
提问by Nick Craver
I have this piece of code, but the values may change while someone is on my site. I would need to update the #finance div every 30 seconds or so. Can this be done?
我有这段代码,但是当有人在我的网站上时,这些值可能会改变。我需要每 30 秒左右更新一次 #finance div。这能做到吗?
$(function() {
$.getJSON(
"http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.quotes%20where%20symbol%20in%20(%22%5EFTSE%22)%0A%09%09&format=json&env=http%3A%2F%2Fdatatables.org%2Falltables.env&callback=?",
function(json){
$('#finance').text(json.query.results.quote.Change);
// Patching payload into page element ID = "dog"
});
});
回答by Alex
You can put your code in a separate function like this:
您可以将代码放在一个单独的函数中,如下所示:
function LoadFinance()
{
$(function() {
$.getJSON(
"http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.quotes%20where%20symbol%20in%20(%22%5EFTSE%22)%0A%09%09&format=json&env=http%3A%2F%2Fdatatables.org%2Falltables.env&callback=?",
function(json){ $('#finance').text(json.query.results.quote.Change);
// Patching payload into page element ID = "dog"
});
});
}
And then set up a timer calling the function every 30 seconds:
然后设置一个计时器,每 30 秒调用一次该函数:
setInterval( LoadFinance, 30000 );
Good luck! ;)
祝你好运!;)
回答by Nick Craver
You can set it on an interval, like this:
您可以将其设置为间隔,如下所示:
$(function() {
function update() {
$.getJSON("http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.quotes%20where%20symbol%20in%20(%22%5EFTSE%22)%0A%09%09&format=json&env=http%3A%2F%2Fdatatables.org%2Falltables.env&callback=?",
function(json){
$('#finance').text(json.query.results.quote.Change);
});
}
setInterval(update, 30000);
update();
});
setInterval()
fires the first time afterthe interval (e.g. it first runs 30 seconds after the DOM loads here)... so for the that initial load, you still need to call it immediately as well via update()
.
setInterval()
在间隔后第一次触发(例如,它在 DOM 加载到此处后 30 秒首次运行)...因此对于初始加载,您仍然需要立即通过update()
.
回答by Mr. TA
Absolutely:
绝对地:
setInterval(
function() {
$.getJSON(
"http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.quotes%20where%20symbol%20in%20(%22%5EFTSE%22)%0A%09%09&format=json&env=http%3A%2F%2Fdatatables.org%2Falltables.env&callback=?",
function(json){ $('#finance').text(json.query.results.quote.Change);
// Patching payload into page element ID = "dog" });
},
30000);