我有一些非常接近我需要的东西,但我一定是错过了什么
下面是我的代码:$.ajax({
url: "http://api.tumblr.com/v2/blog{my-blog}/posts?limit=50",
dataType: 'jsonp',
data: {
api_key: "{my key}"
},
success: function(results){
console.log(results);
var i = 0;
while (i < 50) {
var type = results.response.posts[i].type;
console.log(results.response.posts.length);
if (type == "photo") {
var getImages = results.response.posts[i].photos[i].alt_sizes[0].url;
$("#tumblr-posts").append("<div class='postbody'>" + "<img src=" + getImages + " /></div>");
}
i++;
}
}
});
这是从我的博客返回大尺寸的第一个图像,但我也在控制台上得到一个错误:无法读取未定义的属性'alt_sizes'。我尝试了一些变化,但购买我的逻辑循环应该返回所有posts .posts[I],所有照片。photos[I],然后是alt_sizes[0]数组中的第一个图像,这应该是大图像。
控制台显示正在返回50个对象,因此对API的调用是可以的。
非常感谢任何帮助。
您正在使用计数器i
来选择posts
和photos
的特定属性,这就是为什么它返回未定义的原因,例如:
i = 1;
var getImages = results.response.posts[1].photos[1].alt_sizes[0].url;
posts[1]
是响应中的第二篇文章,但photos[1]
是指posts[1]
的第二张照片,可能不存在,因为它是一个单独的照片帖子。
您需要创建另一个循环来检查每个帖子是否有多于一张照片,photosets将最多有十张照片。
var i = 0;
while (i < 50) {
var type = results.response.posts[i].type;
if (type == "photo") {
var photos = results.response.posts[i].photos;
for (var j = 0; j < photos.length; j++) {
console.log( photos[j].alt_sizes[0].url );
}
}
i++;
}
值得一提的是,在较旧的图像上,如果没有高分辨率的版本可用,它不会回落到另一个URL,它的左空白,所以你可能需要检查一下