如何在客户端检查YouTube上是否存在视频

Hit*_*esh 5 javascript youtube ajax jquery youtube-api

我正在验证我的Youtube网址文字字段.

我需要检查,如果Youtubeurl不存在我应该抛出错误,我按照这个答案并创建了jsfiddle来检查它.

它适用于有效网址但不适用于无效网址.我只看到404错误network console

在此输入图像描述

有没有办法检查客户端是否存在url使用JavaScriptjQuery.

这是我的代码:

var videoID = 'kn8yzJITdvI';//not working 
//var videoID = 'p4kIwWHP8Vc';//working 
$.ajax({
    url: "https://gdata.youtube.com/feeds/api/videos/" + videoID + "?v=2&alt=json",
    dataType: "jsonp",
    success: function(data) {
        console.log(data)
          $("#result").text(data);
    },
    error: function(jqXHR, textStatus, errorThrown)
                    {
                        // Handle errors here
                        alert('ERRORS: ' + textStatus);

                    }
});
Run Code Online (Sandbox Code Playgroud)

JSfiddle Link

Man*_*ora 5

@hitesh,请从ajax请求中删除数据类型:'jsonp'.这样,如果视频ID可用,你将获得json字符串,如果它不可用,那么将调用ajax错误回调.我试过你的小提琴和它的工作.试试这样 -

//var videoID = 'kn8yzJITdvI';//not working 
var videoID = 'p4kIwWHP8Vc';//working 
$.ajax({
    url: "https://gdata.youtube.com/feeds/api/videos/" + videoID + "?v=2&alt=json",
    //dataType: "jsonp",
    success: function(data) {
        console.log(data)
          $("#result").text(data);
    },
    error: function(jqXHR, textStatus, errorThrown)
                    {
                        // Handle errors here
                        alert('ERRORS: ' + textStatus);
                    }
});
Run Code Online (Sandbox Code Playgroud)

以下是您需要的解决方案的另一个简短实施 -

//var videoID = 'kn8yzJITdvI';//not working 
var videoID = 'p4kIwWHP8Vc';//working 

$.getJSON('http://gdata.youtube.com/feeds/api/videos/'+videoID+'?v=2&alt=jsonc',function(data,status,xhr){
    alert(data.data.title);
}).error(function() { alert("error"); });
Run Code Online (Sandbox Code Playgroud)

  • 我如何在 v3 中做到这一点?现在似乎不推荐使用该调用。我得到:{"apiVersion":"2.1","error":{"code":410,"message":"不再可用","errors":[{"domain":"GData","代码":"NoLongerAvailableException","internalReason":"不再可用"}]}} (2认同)
  • @mila看到我的回答[这里](http://stackoverflow.com/questions/1383073/how-do-i-check-if-a-video-exists-on-youtube-using-php?answertab=oldest#tab -最佳) (2认同)

von*_* v. 5

对于那些正在寻找使用 V3 API 的解决方案的人,您可以执行以下操作:

var videoID = 'the_youtube_video_id';
$.getJSON('https://www.googleapis.com/youtube/v3/videos?id=' + videoID 
           + "&key=INSERT_YOUR_API_KEY_HERE&part=COMMA_DELIMITED_VALUE", 
  function (data, status, xhr) {               
    if (data.items.length > 0)
        alert('It is there!')
    else
        alert('Are you sure you about the Id?');

    console.log(status);
    console.log(xhr);
}).error(function (xhr, errorType, exception) {
    var errorMessage = exception || xhr.statusText || xhr.responseText;
    alert(errorMessage);
});
Run Code Online (Sandbox Code Playgroud)

如需有效列表,parts您可以访问此处的文档页面