数组在JSON请求之外消失
我正在尝试使用YouTubevideo的各种属性设置一个数组(您可能认为这有点多余,但我计划将来添加其他来源)。 我可以在JSON请求中将这些值添加到数组中,但是一旦我离开它,它们就会消失。 有任何想法吗?
var socialPosts = new Array(); $.getJSON('https://gdata.youtube.com/feeds/api/videos?author=google&max-results=5&v=2&alt=jsonc&orderby=published', function(data) { for(var i=0; i<data.data.items.length; i++) { //for each YouTube video in the request socialPosts[i]={date:Date.parse(data.data.items[i].uploaded), title:data.data.items[i].title,source:"YouTube", thumbnail:data.data.items[i].thumbnail.hqDefault, url:'http://www.youtube.com/watch?v=' + data.data.items[i].id}; //Add values of YouTube video to array } console.log(socialPosts[0].date); //This returns the correct data }); console.log(socialPosts[0].date); //This returns with undefined
您正在尝试访问尚未返回的Ajax asyn
调用的结果。 您需要在回调函数中使用结果或将结果传递给某个函数 。
var socialPosts = new Array(); $.getJSON('https://gdata.youtube.com/feeds/api/videos?author=google&max-results=5&v=2&alt=jsonc&orderby=published', function(data) { for(var i=0; i
因为这是一个Ajax函数,它发生异步意味着闭包之外的代码在调用完成之前执行