使用JSON和jQuery获取带有链接,回复或主题标签的推文

时间:2012-04-26 16:43:25

标签: jquery json twitter

我正在开发一个用户输入随机单词并获取相关推文列表的网站。

如何使用json获取包含链接,回复或主题标签的推文?

这是我的jQuery代码:

        <script>

        function go(){
          var url = "http://search.twitter.com/search.json?callback=results&q=" + $("#text").val();
          $("<script/>").attr("src", url).appendTo("body");  
            $("#text").remove();
        }

        $("#text").keydown(function(e){ if( e.which == 13 )  go(); });

        function results(r){
          window.results = r.results;
          window.theIndex = 0;
          displayNext();
        }
        function displayNext(){
          if( window.theIndex >= window.results.length ){
            return;
          }
          $('.content').remove();
            $('.helper').remove();
          createDiv( window.results[window.theIndex] );
          window.theIndex++;
          setTimeout(displayNext, 4000);
        }

        function createDiv(status){
          var tweets = status.text;
          $("<span class='content'>")
          .html(tweets)
          .appendTo("body");
          $("<span class='helper'>")
          .appendTo("body")
        }

        </script>

1 个答案:

答案 0 :(得分:0)

根据Dev Twitter API reference,返回的JSON对象包含result属性,该属性是表示所有推文的JSON对象数组。这些特别感兴趣的JSON数组中的两个属性是entitites属性和to_user_id属性。因此,要检查推文是否不是回复且不包含任何链接,您将检查entities是否为空对象且to_user_id为空。

displayNext功能更改为此功能应该有效:

function displayNext(){
    if( window.theIndex >= window.results.length ){
        return;
    }
    $('.content').remove();
    $('.helper').remove();
    var result = window.results[window.theIndex];
    if (Object.keys(result.entities).length !== 0 && result.to_user_id === null) {
        createDiv( window.results[window.theIndex] );
        window.theIndex++;
        setTimeout(displayNext, 4000);
    }
}​

(请注意,我正在使用How do I test for an empty JavaScript object?的答案来检查entitites是否为空对象。)