Hit*_*esh 5 javascript youtube ajax jquery youtube-api
我需要检查,如果Youtubeurl不存在我应该抛出错误,我按照这个答案并创建了jsfiddle来检查它.
它适用于有效网址但不适用于无效网址.我只看到404错误network console

有没有办法检查客户端是否存在url使用JavaScript和jQuery.
这是我的代码:
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)
@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 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您可以访问此处的文档页面。
| 归档时间: |
|
| 查看次数: |
8335 次 |
| 最近记录: |