如何重新加载JSON与AJAX每10秒加载、JSON、AJAX

2023-09-11 01:28:19 作者:南港清风

我试图用jQuery重新加载一个JSON文件每隔10秒。

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

该网页是在这里: http://moemonty.com/chirp/chirp.html

在code是在这里:

<html>
<head>
<title>the title</title>
 <!-- included Jquery Library -->
    <script type="text/javascript" src="./js/jquery-1.4.2.js"></script>
 <!-- jquery library -->
  </head>
<body>  
 <script>

$.ajaxSetup({ cache: false }); //disallows cachinge, so information should be new


function loadChirp(){ //start function

var url = "http://www.chirpradio.org/json";
        $.getJSON("http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20json%20where%20url%3D%22"+url+"%22&format=json&callback=?", 
            function(data){
            console.log(data.query.results.json);

                document.write('The artist is: ' + data.query.results.json.artist + '<br/><br/>');

                document.write('The artist is: ' + data.query.results.json["record-label"] + '<br/><br/>' );

                document.write('The album is: ' + data.query.results.json.album + '<br/><br/>');

                document.write('The record label is: ' + data.query.results.json["record-label"] + '<br/><br/>');

                document.write('The feedback link is: ' + data.query.results.json["feedback-link"] + '<br/><br/>');

                document.write('The database id is: ' + data.query.results.json["database-id"] + '<br/><br/>');

                document.write('The time is: ' + data.query.results.json.timestamp.time + ' ');

                document.write(data.query.results.json.timestamp["am-pm"] + '<br/><br/>');

                document.write('The current dj is: ' + data.query.results.json["current-dj"] + '<br/><br/>');


                setTimeout("loadChirp()",5000);
                alert('The timeout was triggered.');

            }); 

} //end function        


$(document).ready(function(){ 
//DOCUMENT READY FUNCTION
    loadChirp();
}); 
//DOCUMENT READY FUNCTION 


</script>  
</body>
</html>

这似乎并不奏效。

It doesn't seem to be working.

推荐答案

您可能希望而不是进行附加的previous集科组新的替换返回的数据。在这种情况下,使用jQuery你可以这样做:

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...