14

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

3 回答 3

38

您可以将代码放在单独的函数中,如下所示:

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 );
于 2010-12-15T13:53:24.883 回答
19

您可以将其设置为间隔,如下所示:

$(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().

于 2010-12-15T13:52:01.563 回答
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);
于 2010-12-15T13:52:36.503 回答