我如何检查是否存在的视频在YouTube上,在客户端 [英] How do I check if a video exists on YouTube, in client side
问题描述
I am doing validation for my Youtube
url text field.
我需要检查,如果的Youtube
URL不存在我应该抛出错误,我跟这个的答案并创建了的jsfiddle 进行检查。
I need to check, if the Youtube
url does not exist I should throw error, I followed this answer and created the jsfiddle to check it.
它适用于有效的URL,但它不会为无效的网址工作。我看到的是404错误网络控制台
It works for valid url but it does not work for invalid url. All I see is 404 error in network console
有没有一种方法来检查,如果网址在客户端存在使用的JavaScript
和的jQuery
。
Is there a way to check if url exist in client side using JavaScript
and jQuery
.
这是我的code:
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,请删除数据类型:JSONP从Ajax请求。这样你会得到JSON字符串,如果视频ID可用,如果不可用,AJAX错误回调会被调用。我想在你的小提琴,它的工作。尝试这样的 -
@hitesh, Please remove the datatype:'jsonp' from the ajax request. This way you'll get json string if the video id is available and if its not available then the ajax error callback would be invoked. I tried on your fiddle and its working. Try like this-
//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);
}
});
下面是另一个短期实现你所需要的解决方案 -
Here is another short implementation for the solution you need-
//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"); });
这篇关于我如何检查是否存在的视频在YouTube上,在客户端的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!