当前使用下面的代码从 YouTube 上的搜索中获取第一个视频,但是当调用 docready 时,未设置 id。该代码不会等待 ajax 结果返回,而是继续执行并且不返回任何内容。
我已经尝试过 async:false 和 ajax ,认为它可能会使其“等待”,但仍然没有返回任何内容。我该如何解决这个问题以便设置所有 id?
$(document).ready(function () {
docready();
});
function docready() {
var id1 = grabid("cat");
var id2 = grabid("dog");
var id3 = grabid("goldfish");
alert(id1);
}
function grabid(keyword) {
var url = 'http://gdata.youtube.com/feeds/api/videos?q=' + encodeURIComponent(keyword) + '&format=5&max-results=1&v=2&alt=jsonc';
$.ajax({
async: false,
type: "GET",
url: url,
dataType: "jsonp",
success: function (responseData, textStatus, XMLHttpRequest) {
if (responseData.data.items) {
var videos = responseData.data.items;
videoid = videos[0].id;
alert(videoid);
return videoid;
}
}
});
}
更新:我刚刚对上面的代码进行了一些更改,以使我的问题更加清晰。当代码运行时,它会按预期警告真正的“videoid”3 次。但是当它到达alert(id1)时,它返回未定义 - 因此“返回videoid”被忽略并且不会将其传递回变量。
更新 2 仍未解决
最佳答案
首先,你的ajax调用有问题,试试这个..
$.ajax({
type: "GET",
url: url,
dataType: "jsonp",
success: function (responseData) {
var videos = responseData.data.items;
var videoid=videos[0].id;
alert(videoid);
//pass this videoid to anyother JS function it should work
},
error: function (xhr, textStatus, XMLHttpRequest) {
alert(xhr.responseText);
}
});
编辑:
更新了代码以从 ajax 调用获取返回:
function grabid(keyword){
var url = 'http://gdata.youtube.com/feeds/api/videos?q='+encodeURIComponent(keyword)+'&format=5&max-results=1&v=2&alt=jsonc';
return $.ajax({
type: "GET",
url: url,
dataType: "jsonp"
});
}
function getVideoId(key) {
key.success(function(respdata) {
var videos = respdata.data.items;
var videoid=videos[0].id;
alert(videoid)
});
}
var ids = grabid(123);
getVideoId(ids);
删除所有加载或文档就绪功能,这应该可以工作。
编辑:
你唯一能做的就是执行 async:false ,它将等待 ajax 调用完成并返回一个值...但是跨域调用不是同步的,所以我可以说你运气不好..你需要重新思考ajax调用的逻辑。
此外,从 jQuery 1.8 开始,不推荐使用 async: false。
关于javascript - YouTube API : How to grab video ID? JQuery/Json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11484938/