使用JSON和JQuery获取Twitter Feed - 自动刷新?

use*_*774 2 twitter jquery json refresh

我正在编写一个脚本,它将从Twitter API"获取"最新的推文,然后使用JQuery在我的页面上将它们显示为HTML.

我是JQuery的新手,所以如果有人能指出我在JQuery网站上必要功能的方向,我将非常感激.

我目前已经构建了以下脚本:

<!-- Use the Google jQuery CDN for lib support -->
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<!-- Setup and fetch the JSON data -->
<script type="text/javascript">
$(document).ready(function(){
var url='http://search.twitter.com/search.json?callback=?&q=@req';
$.getJSON(url,function(json){
<!-- Iterate the file -->
        $.each(json.results,function(i,tweet){
           $("#results").append('<p><img src="'+tweet.profile_image_url+'" widt="48" height="48" />'+tweet.text+'</p>');
$("#results").slideDown("slow");
        });
                    });
});
</script>
<!-- Output the file into the DIV -->
<div id="results"></div>
Run Code Online (Sandbox Code Playgroud)

该脚本工作正常,但我现在想要结合某种形式的内容自动刷新.即每x分钟"重新获取"一次.

根据我的理解,我需要用.html替换.append,以便在重新加载之前从页面中删除内容,但是有没有人对实际获取内容的最佳方式有任何建议?我发现可能有文章表达了对浏览器内存泄漏的担忧等,并且不想走错路.

我期待你的回复,再次感谢.

Jas*_*per 6

$(function(){
    function getTweets() {
        var url='http://search.twitter.com/search.json?callback=?&q=@req';
        $.getJSON(url,function(json){

            //setup an array to buffer output
            var output = [];

            //a for loop will perform faster when setup like this
            for (var i = 0, len = json.results.length; i < len; i++) {

               //instead of appending each result, add each to the buffer array
               output.push('<p><img src="' + json.results[i].profile_image_url + '" widt="48" height="48" />' + json.results[i].text + '</p>');
            }

            //now select the #results element only once and append all the output at once, then slide it into view
            $("#results").html(output.join('')).slideDown('slow');
        });
    }

    //set an interval to run the getTweets function (30,000 ms is 5 minutes), you can cancel the interval by calling clearInterval(timer);
    var timer = setInterval(getTweets, 30000);

    //run the getTweets function on document.ready
    getTweets();

});
Run Code Online (Sandbox Code Playgroud)

以下是一些很好的文档window.setInterval():https://developer.mozilla.org/en/window.setInterval

  • 为了确保你没有堆叠调用,以防服务器响应缓慢,我想最好使用setTimeout,然后从getTweets内部设置一个新的超时,在X秒后再次调用自身 - 在AJAX之后通话已完成.50秒后,我猜你也可以使用setInterval,但如果他想每10秒运行一次,那么AJAX调用就有可能排队. (2认同)