每隔30秒jQuery Ajax请求

时间:2010-12-15 13:49:36

标签: jquery ajax yql

我有这段代码,但当某人在我的网站上时,这些值可能会发生变化。我需要每隔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"
        });
});

3 个答案:

答案 0 :(得分:33)

您可以将代码放在一个单独的函数中:

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" 
        });
    });
}

然后设置一个定时器,每隔30秒调用一次该函数:

setInterval( LoadFinance, 30000 );
祝你好运! ;)

答案 1 :(得分:18)

您可以按照以下间隔设置它:

$(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()第一次间隔后触发(例如,它在DOM加载后第一次运行30秒)...所以对于那个初始加载,你仍然需要调用它也会立即通过update()

答案 2 :(得分:3)

绝对:

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);