数组在JSON请求之外消失
Arrays disappear outside of JSON request
我试图设置一个数组与YouTube视频的各种属性(您可能认为这是有些多余的,但我计划在未来添加其他来源)。我能够将这些值添加到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
调用的结果,这些结果尚未返回。您需要在中使用result回调函数或将结果传递给某些函数。
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
somefun(socialPosts[0].date);
});
因为这是一个Ajax函数,它是异步发生的这意味着闭包外的代码在调用完成之前执行
相关文章:
- ajax请求的顺序总是不同的
- Meteor如何接收HTTP请求
- 有没有一种方法可以防止img get请求使用css或js发生
- 从ajax请求中获取javascript对象
- facebook”;添加评论“;popup获胜'不要消失
- JSONP请求返回结果,但也触发error_callback
- 在localhost Dev Box上测试JSONP请求的最佳方式
- Ajax请求文档就绪会导致jquery加载缓慢
- 为什么js事件消失了
- MockJax没有在JavaScript应用程序中发送对我AJAX请求的响应
- 正在传递JSONP标头's数据参数到另一个文件中的AJAX请求
- 在openshift node js应用程序中获取请求
- 反应路由器弄乱了请求网址
- JS文件的路径正在消失
- 在我的情况下,如何进行http请求
- 将phonegap图像发布到php/mysql-图像字段从发布请求中消失
- 数组在JSON请求之外消失
- Primefaces<p: 工具提示>不会在另一个Ajax请求后消失
- GAE 会话在来自 JavaScript 的 POST 请求后消失
- 我的网页加载,然后立即消失.在chrome开发工具中,没有坏的请求