如何每10秒用AJAX重新加载JSON

我正在尝试使用JQUERY每10秒重新加载一个JSON文件。

该页面位于: http : //moemonty.com/chirp/chirp.html

守则在这里:

  the title       $.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 + '

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

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

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

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

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

'); document.write('The time is: ' + data.query.results.json.timestamp.time + ' '); document.write(data.query.results.json.timestamp["am-pm"] + '

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

'); setTimeout("loadChirp()",5000); alert('The timeout was triggered.'); }); } //end function $(document).ready(function(){ //DOCUMENT READY FUNCTION loadChirp(); }); //DOCUMENT READY FUNCTION

它似乎没有工作。

您可能希望先前的一组返回数据被新集替换,而不是附加它。 在这种情况下,使用jQuery你可以做到:

 

等等…

我希望循环可以作为引用工作,但是你可能会使用JSONP。 我会将setTimeout调用更改为:

 setTimeout(loadChirp, 5000); 

……有几个原因。 首先,使用函数引用而不是代码字符串通常是一个更好的主意,其次,你很确定你正在获得正确的函数引用(而对于字符串,你得到的引用取决于上下文其中执行代码)。

但正如Pointy在评论中指出的那样,还有一个单独的问题: document.write不会做你想做的事情。 您只能使用document.write写入正在作为原始页面加载的一部分进行分析的HTML流。 页面加载后,您将无法再使用它。 考虑使用jQuery的appendappendTo以及类似的函数在页面加载后添加到DOM。

你在console.log(data.query.results.json);有错误console.log(data.query.results.json); – 未定义控制台。 另外,你可以使用setInterval( "function()", 5000 );

你一定要用:

setInterval(“loadChirp”,10000):

不要在setInterval中写入loadCrirp(),因为我们只传递了一个引用