jQuery Ajax request every 30 seconds

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-17 07:31:32

问题


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?

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

回答1:


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:

setInterval( LoadFinance, 30000 );

Good luck! ;)




回答2:


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 after the 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().




回答3:


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


来源:https://stackoverflow.com/questions/4450579/jquery-ajax-request-every-30-seconds

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!