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

How do I check if a video exists on YouTube, in client side

我在做

我需要检查,如果 Youtube url 不存在我应该抛出错误,我按照这个 answer and created the jsfiddle 来检查它。

它适用于有效 url 但它不适用于无效 url。我只看到 network console

中的 404 错误

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

这是我的代码:

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);

                    }
});

JSfiddle Link

这是一个已知问题,请参阅

jQuery Ajax 404 Handling

http://forum.jquery.com/topic/jquery-ajax-with-datatype-jsonp-will-not-use-error-callback-if-request-fails

来自$.ajax docs

错误

Note: This handler is not called for cross-domain script and cross-domain JSONP requests.

有人遇到过和你一样的问题,跨域请求时无法检查404错误。你应该通过超时来处理它。

JSONP request error handling

在客户端试试这个:

//here, oABCD01234 is YouTube id
$.ajax({
    type: 'HEAD',
    url: 'http://gdata.youtube.com/feeds/api/videos/oABCD01234',
    success: function() {
        //it exists!
    },
    error: function(jqXhr) {
        if(jqXhr.status == 400) {
            //it doesn't exist
        }
    }
});

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

//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);
                    }
});

这是您需要的解决方案的另一个简短实现-

//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"); });

对于正在寻找使用 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);
});

要获得有效 parts 的列表,您可以访问 the doc page here