问题:我想从REST API调用中获取数据并将其分配给一个变量,并将其用作另一个函数或目的的输入。将数据从REST YOUTUBE DATA API 3分配给回调之外的变量函数Jquery
功能:
function getSongName(id, callback) {
var apikey = {My_TOKEN};
var fetchInformation = "https://www.googleapis.com/youtube/v3/videos?key=" +apikey +"&fields=items(snippet(title" +"))&part=snippet&id=" +id;
$.getJSON(fetchInformation, function (jsonData) {
fullname = jsonData.items[0].snippet.title;
callback(fullname);
});
}
我打电话在另一个地方这个功能与
var title = getSongName(youtubeID, function(name) {
console.log("song name is :"+name);
});
我得到的console.log值的要求。 现在我想用这个标题
z.innerHTML = '<b>' + title + 'num: ' + j + '</b>';
这里j
是从别的地方来,所以我不能用它的“getSongName”电话里面。
有没有一种方法不仅仅是在console.log
里面,而是实际上将“名称”赋值给另一个变量并将其用作我想要的以上?
我不知道是否有另一种方式做到这一点,我没有遇到过,但任何帮助将不胜感激。
解决----------- STEPS下面提到
function getSongName(youtubeID, idForPlayer,i, z, callback) {
var apikey = {My_TOKEN};
var fetchInformation = "https://www.googleapis.com/youtube/v3/videos?key=" +apikey +"&fields=items(snippet(title" +"))&part=snippet&id=" +id;
//$.ajaxSetup({'async':false}); WILL return the value for each loop and not do it asynchronously which had me pulling my hair out. P.S. this was the reason only one value was being returned
$.ajaxSetup({'async':false});
$.getJSON(fetchInformation, function (jsonData) {
debugger;
var fullname = jsonData.items[0].snippet.title;
boolean = false;
if (fullname) {
boolean = true;
if (boolean){
console.log("song name inside the gerSongName loop is: " + i +" ", fullname);
callback(fullname);
}
debugger;
}
else {
debugger;
console.log("No song name");
}
});
}
然后在循环中我叫上述功能让我值运行另一个函数内。
getSongName(youtubeID, idForPlayer,i, z, function(name) {
z.innerHTML = '<b>' + name + '</b>';
debugger;
document.getElementById('elementTagID').appendChild(z);
});
希望这可以帮助别人。 谢谢。
可能重复[如何返回来自异步调用的响应?](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call ) –