2015-06-05 54 views
0

我遇到新的YouTube API問題。與版本2通過ajax調用,我可以把最後一個視頻上傳到播放列表,我該如何處理新的API?感謝您的支持 。YouTube API v3加載播放列表中的最後一個視頻

編輯

感謝您的回答,我嘗試了代碼,但返回一個JavaScript錯誤:「無法讀取屬性未定義 'setApiKey'」下面的HTML代碼:

<!doctype html> 
<html> 
    <head> 
    <title>YouTube</title> 
    </head> 
    <body>  
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script> 
    <script src="https://apis.google.com/js/client.js?onload=handleClientLoad"></script> 

    <script>  
     gapi.client.setApiKey('{API-KEY-HERE}'); 
     gapi.client.load('youtube', 'v3', function() { 

      var request = gapi.client.youtube.playlistItems.list({ 
       part: 'snippet', 
       playlistId: 'PLTK1i0pncVu_tLhgrPo_o7QcRocqozxUv' 
      }); 

      request.execute(function (response) { 
       response.items.sort(function(a,b) {return a.snippet.publishedAt < b.snippet.publishedAt}) 

       for (var i=0; i<response.items.length;i++) 
       { 
        console.log(response.items[i].snippet.title + " published at " + response.items[i].snippet.publishedAt) 
       } 
      }); 
     }); 
    </script> 


    </body> 
</html> 

回答

0

像這樣的東西會加載指定播放列表的所有視頻,並按publishedAt排序。對於最新的視頻只需要第一個結果。

<!doctype html> 
<html> 
<head> 
    <title>YouTube</title> 
</head> 

<body> 

    <script> 
     var allVideos = new Array(); 

     function onGoogleLoad() { 
      gapi.client.setApiKey('{YOUR-API-KEY}'); 
      gapi.client.load('youtube', 'v3', function() { 

       GatherVideos("", function() { 

        allVideos.sort(function(a, b) { 
         return Date.parse(b.snippet.publishedAt) - Date.parse(a.snippet.publishedAt); 
        }) 

        for (var i = 0; i < allVideos.length; i++) { 
         console.log(allVideos[i].snippet.title + " published at " + allVideos[i].snippet.publishedAt) 
        } 
       }); 
      }); 
     } 

     function GatherVideos(pageToken, finished) { 
      var request = gapi.client.youtube.playlistItems.list({ 
       part: 'snippet', 
       playlistId: 'PLTK1i0pncVu_tLhgrPo_o7QcRocqozxUv', 
       maxResults: 50, 
       pageToken: pageToken 
      }); 

      request.execute(function(response) { 
       allVideos = allVideos.concat(response.items); 
       if (!response.nextPageToken) 
        finished(); 
       else 
        GatherVideos(response.nextPageToken, finished); 
      }); 
     } 
    </script> 

    <script src="https://apis.google.com/js/client.js?onload=onGoogleLoad"></script> 

</body> 

</html> 
+0

感謝您的回答@theduck,我嘗試了代碼,但返回一個JavaScript錯誤:「不能讀取屬性‘setApiKey’的未定義」成我的評論的HTML代碼 – Mic

+0

行 - 我有再看看此代碼並試圖改進它。我添加了分頁功能(YouTube API僅返回最多50個視頻,這對您的播放列表來說是一個問題)。希望這現在應該對你有用。如果他們將「排序」選項添加到請求中,會更容易! – theduck

相關問題