jQuery - 抓住youtube标题,等待下载标题

时间:2017-07-28 19:12:17

标签: javascript jquery html youtube-api

我正在尝试抓取YouTube视频的标题并将其打印在该视频的缩略图下的页面上。

一切正常,我获得了API密钥,标题正在打印到控制台。但它完成了Ajax所以我必须让一切都等待标题的到来。那就是我被困住的地方。

那么如何让代码/循环等待Ajax完成呢?

我的简化代码。我尝试将它发布在代码笔上,但没有运气使js工作。 https://codepen.io/anon/pen/JyYzwM

使用它链接到实际页面。它在那里工作,你可以看到控制台返回标题。 http://boiling-everglades-49375.herokuapp.com/video.php

$('.category-shape').on('click', function () {
   var documentary = ["siAPGGuvPxA", 'i6Hgldw1yS0', 'Omg1gMNtVpY', 'MfWHPnxrDI4', 'aT0HduxW8KY'];
   showVideos(documentary);
}


function showVideos(channel) {
if (!isFirstPass) {
    $('#addedContent').remove();
}
$('#dropdownVideoPicker').append('<div id="addedContent"></div>');
console.log(" ");
for (var i = 0; i < channel.length; i++) {
    var title = getTitle(channel[i]);
    $.when(getTitle(channel[i])).done( function () {
        var pageCode = generatePageCode(channel[i], title);
        console.log(getTitle(channel[i]));
        $('#addedContent').append(pageCode);
    });
}
$('#addedContent').hide();
$('#addedContent').slideDown();
isFirstPass = false;
$("html, body").animate({scrollTop: ($('.category-shape:nth-of-type(6)').offset().top)}, 1000);
grabYtId();
}


function grabYtId() {
    $('.videoThumbnail').on('click', function () {
      var $ytId = $(this).attr('src').slice(27, -6);
      showModalWindow($ytId);
    });
}


function showModalWindow(Id) {
var $theModal = $("#videoModal"),
    iframe = $("#iframe")[0],
    videoSRC = 'https://www.youtube.com/embed/' + Id,
    videoSRCauto = videoSRC + "?autoplay=1&rel=0&controls=1&showinfo=0";
$(iframe).attr('src', videoSRCauto);
$('button.close').click(function () {
    $(iframe).attr('src', videoSRC);
});
$theModal.on("hidden.bs.modal", function () {
    $(iframe).attr('src', videoSRC);
});
}

这就是抓住标题的功能

function getTitle(videoId) {
$.ajax({
    url: "https://www.googleapis.com/youtube/v3/videos?id=" + videoId + "&key=" + "AIzaSyCDyE576FU2QRbkHivxHfrjbEjPwartzKo" + "&fields=items(snippet(title))&part=snippet",
    dataType: "jsonp",
    success: function (data) {
        var title = data.items[0].snippet.title;
        console.debug("function: " + title);
        var titleLoaded = new CustomEvent('titleLoaded', {
            detail: {
                loaded: true
            }
        });
        $('body')[0].dispatchEvent(titleLoaded);
        return title;
    },
    error: function (jqXHR, textStatus, errorThrown) {
        alert(textStatus, +' | ' + errorThrown);
    }
});
}

是的,我知道向公众提供API密钥是一个坏主意,但我会更改它在谷歌中添加网站限制。

1 个答案:

答案 0 :(得分:2)

您可以在阵列中推送ajax deffered对象并调用$.when.apply($,arr) 以等待处理所有调用:

function showVideos(channel) {

  if (!isFirstPass) {
    $('#addedContent').remove();
  }
  $('#dropdownVideoPicker').append('<div id="addedContent"></div>');

  var arr = $.map(channel, function(data) {
    getTitle(data);
  });

  $.when.apply($, arr).then(function() {
    $('#addedContent').hide();
    $('#addedContent').slideDown();
    isFirstPass = false;
    $("html, body").animate({
      scrollTop: ($('.category-shape:nth-of-type(6)').offset().top)
    }, 1000);
    grabYtId();
  });
}

function getTitle(videoId) {

  return $.ajax({
    url: "https://www.googleapis.com/youtube/v3/videos?id=" + videoId + "&key=" + "AIzaSyCDyE576FU2QRbkHivxHfrjbEjPwartzKo" + "&fields=items(snippet(title))&part=snippet",
    dataType: "json",
    success: function(data, status, jqxr) {
      var title = data.items[0].snippet.title;
      var titleLoaded = new CustomEvent('titleLoaded', {
        detail: {
          loaded: true
        }
      });
      $('body')[0].dispatchEvent(titleLoaded);
      var pageCode = generatePageCode(videoId, title);
      console.log(title);
      $('#addedContent').append(pageCode);
    },
    error: function(jqXHR, textStatus, errorThrown) {
      alert(textStatus, +' | ' + errorThrown);
    }
  });
}

你可以找到一个小提琴here