JQuery: combine multiple JSON results

Situation: A user wants to import a Youtube playlist on a JQuery website using the Youtube JSON API.

Problem: Youtube returns only the first 50 entries, but playlists can be longer than 100 entries (the length is determined by "totalItems" in the JSON response). All records should be combined as one object and should be pressed into the output function at the end.

Record 1-50: http://gdata.youtube.com/feeds/api/playlists/84780DAC99E1A285?v=2&alt=jsonc&max-results=50&start-index=1

Record 50-100: http://gdata.youtube.com/feeds/api/playlists/84780DAC99E1A285?v=2&alt=jsonc&max-results=50&start-index=50

Current code:

function fetchPlaylist(pid) {
    var the_url = 'http://gdata.youtube.com/feeds/api/playlists/' + encodeURIComponent(pid) + '?v=2&alt=jsonc&max-results=50';
    $.ajax({
        type: "GET",
        url: the_url,
        dataType: "jsonp",
        success: function (responseData, textStatus, XMLHttpRequest) {
            if (responseData.data != null) {
                if (responseData.data.items) {
                    outputFunction(responseData.data.items);
                } else {
                    console.log('No results for playlist: "' + pid + '"');
                }
            }
        }
    });
}

Question:

  • JSON , ?

  • ?

:

http://api.jquery.com/jQuery.extend/ - /

+4
3

, , $.merge() :

function fetchPlaylist(pid, start, items) {
  items = items || [];
  start = start || 0;
  var the_url = 'http://gdata.youtube.com/feeds/api/playlists/' + encodeURIComponent(pid) + '?v=2&alt=jsonc&max-results=50';
  $.ajax({
      type: "GET",
      url: the_url,
      data: { start: start },
      dataType: "jsonp",
      success: function(responseData, textStatus, XMLHttpRequest) {
        if (responseData.data != null) {
          if (responseData.data.items) {
            $.merge(items, responseData.data.items); //add to items
            if (responseData.data.totalItems > start + 50) {
                fetchPlaylist(pid, start + 50, items);
            } else {
                outputFunction(items);
            }
          } else {
            console.log('No results for playlist: "' + pid + '"');
          }
        }
      }
  });
}

, , :

fetchPlaylist("84780DAC99E1A285");​

, , , totalItems, youtube, , 50, , ... , outputFunction().

+4
  • start-index Google. , fetchPlaylist() , , .

  • . extend(),

+1

- . +50, count(responseData.data.items), API YouTube?

I know that a JSON request is called using max-results=50, but they may start to limit this to fewer elements.

0
source

All Articles