2017-10-17 112 views
0

我不明白爲什麼items數組爲空。有人能告訴我什麼不工作嗎?謝謝。來自YouTube API請求的空結果

jQuery(document).ready(function ($) { 

$('#infl-yt-label').on('click', function() { 
    //$('#infl-inp-search').attr("placeholder","YouTube input..."); 
    $('#infl-form-ig').hide(); 
    $('#infl-form-yt').show(); 
}); 

$('#infl-it-label').on('click', function() { 
    //$('#infl-inp-search').attr("placeholder","Instagram input..."); 
    $('#infl-form-yt').hide(); 
    $('#infl-form-ig').show(); 
}); 

$("#searchchannels").on("click", function() { 
    console.log($("#infl-inp-search-yt").val()); 
    $.get(
     "https://www.googleapis.com/youtube/v3/search?", 
     { 
      part:"snippet", 
      type:"channel", 
      q: encodeURIComponent($("#infl-inp-search-yt").val()).replace(/%20/g, "+"), 
      key:key 
     }, 
      function(data) 
      { 
       console.log(data.items) 
       $.each(data.items, function() 
       { 
       console.log(data.items); 
       }) 
      } 

     );//end get 
    alert(1); 
});//end 

});// end 

HTML:

 <div class="infl-sociale col-md-3 col-lg-2 text-center"> 
      <input id="infl-yt" type="radio" name="infl-sociale" value="youtube" checked> 
      <label for="infl-yt" id="infl-yt-label"><i class="fa fa-youtube-play" aria-hidden="true"></i></label> 
      <input id="infl-it" type="radio" name="infl-sociale" value="instagram"> 
      <label for="infl-it" id="infl-it-label"><i class="fa fa-instagram" aria-hidden="true"></i></label> 
     </div> 

注:我沒有腳本的鏈接在標題中的谷歌API的鏈接。

+0

也許assync錯誤的回調或回調不解析爲JSON。 –

+1

你沒有在你的'each'函數中傳遞數據,只需要添加'$ .each(data.items,function(data)' – Grasper

+0

@Grasper,我試過你的解決方案,它不起作用。 –

回答

0

您應更新函數以正確遍歷「items」集合。

function(data) 
{ 
    console.log(data.items) /* what does this log to the console? */ 
    $.each(data.items, function(item) 
    { 
     console.log(item); 
    }) 
} 

話雖這麼說,什麼是第一console.log(data.items)的結果呢?如果這是空的,迭代它不會做任何事情。您也可以嘗試console.log(data)或查看Chrome調試網絡選項卡以查看API調用的響應。