How to reload JSON with AJAX every 10 Seconds

后端 未结 4 2003
小蘑菇
小蘑菇 2021-02-06 06:55

I\'m trying to reload a JSON file every 10 seconds with JQUERY.

The page is here: http://moemonty.com/chirp/chirp.html

The Code is here:



        
相关标签:
4条回答
  • 2021-02-06 07:22

    You should definitely use:

    setInterval("loadChirp", 10000):

    Don't write loadCrirp() inside setInterval as we're only passing a refrence

    0 讨论(0)
  • 2021-02-06 07:31

    I would expect the loop to work as quoted, but there could be a subtlety around the fact you're using JSONP. I would change the setTimeout call to:

    setTimeout(loadChirp, 5000);
    

    ...for a couple of reasons. First off, using the function reference rather than a code string is a better idea generally, and second off, you're quite certain that you're getting the right function reference (whereas with the string, what reference you get depends on the context in which the code is executed).

    But as Pointy pointed out in a comment, there's a separate issue: document.write will not do what you probably want it to do there. You can only use document.write to write to the HTML stream that's being parsed as part of the original page load. After the page load, you can't use it anymore. Consider using jQuery's append or appendTo and similar functions to add to the DOM after page load.

    0 讨论(0)
  • 2021-02-06 07:33

    You probably want the previous set of returned data replaced by the new set, instead of appending it. In that case, using jQuery you can do:

    <div id='content'></div>
    <script>
         function loadChirp(){
             $.getJSON("http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20json%20where%20url%3D%22"+url+"%22&format=json&callback=?", 
                  function(data) {
                      $('#content').html('The artist is: ' + data.query.results.json.artist + '<br/><br/>');
                  }); 
             setTimeout("loadChirp()",5000);
          }
    </script>
    

    etc...

    0 讨论(0)
  • 2021-02-06 07:35

    You have an error in console.log(data.query.results.json); - console is not defined. Also, you can use setInterval( "function()", 5000 );.

    0 讨论(0)
提交回复
热议问题