我在做validation for my Youtube
url text field。
我需要检查,如果Youtube
网址不存在,我应该抛出错误,我遵循了这个answer并创建了jsfiddle进行检查。
它适用于有效的网址,但不适用于无效的网址。我所看到的是network console
中的404错误
有没有一种方法可以使用JavaScript
和jQuery
检查客户端中的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'。这样,如果视频ID可用,则将获取json字符串;如果视频ID不可用,则将调用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"); });