2012-04-26 29 views
2

讓他們當我正在開發一個網站,用戶輸入一個隨機單詞,並得到相關的微博列表答覆或井號標籤。跳過鳴叫的鏈接,使用JSON和jQuery

如何在使用json提取包含鏈接,回覆或主題標籤的Twitter消息時排除推文?

這裏是我的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> 

回答

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是一個空的對象)

+0

不幸的是,這並不」工作。 – Sergey 2012-06-18 08:58:32