如何检查YouTube上的video是否存在于客户端

我正在validation我的Youtubeurl文字字段 。

我需要检查,如果Youtubeurl不存在,我应该抛出错误,我按照这个答案创建了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

@hitesh,请从ajax请求中删除数据类型:’jsonp’。 这样,如果videoID可用,你将获得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); } }); 

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

 //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的列表,您可以访问此处的文档页面 。

来自$ .ajax docs :

错误

注意:不会为跨域脚本和跨域JSONP请求调用此处理程序。

有人已经遇到了与您相同的问题,在进行跨域请求时无法检查404错误。 你应该通过超时处理它。

JSONP请求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 } } });