2013-09-25 53 views
1

我正在尝试使用Tumblr API实现照片供稿。到目前为止,它的工作原理与只是文本,但是当我尝试照片我得到的错误Tumblr API:'Can not read property'alt_sizes'of undefined'

Cannot read property 'alt_sizes' of undefined

我不知道如何去纠正我的代码来解决这个问题。我的代码是:

$.ajax({ 
    url: "http://api.tumblr.com/v2/blog/myblog.tumblr.com/posts?api_key=key&tag=offers", 
    dataType: 'jsonp', 
    success: function(results){ 

    var i = 0; 

    while (i < 10) { 

     var type = results.response.posts[i].type; 
     var date = results.response.posts[i].date; 
     var link = results.response.posts[i].post_url; 

     if (type == "photo") { 
     var photourl = results.response.posts[i].photos[i].alt_sizes[i].url; 
     $("#tumoffers").append("<div class='tumpost'><a href='" + link + "'><img src='" + photourl + "' alt='" + title + "'/></a></div>"); 
     } 

     i++; 
    }//END WHILE 

    }//END RESULTS FUNCTION 
}); 

在的tumblr的API文档我看到alt_sizes转化为图像的大小看,但我不想使用这个属性。

有谁知道如何让API忽略这个属性?

回答

1

我发现它得到了一个错误,因为你可以为每个岗位多张照片,所以行

.photos[i].alt_sizes[i]

实际上是在不同的数组中,在主要数组中。

在我来说,我只是用平均每个职位1张照片,所以我只是把它改成

.photos[0].alt_sizes[0]

但要正确地做到这一点,你应该创建另一个回路平均每个职位的照片。

1

你可以使用hasOwnProperty实际上是试图访问它,像以前一样,以检查是否存在此类属性:

var data = results.response, 
    i = results.response.total_posts; //this gives total posts you have 
while (i < 10) { 
    var type = data.posts[i].type, 
     date = data.posts[i].date, 
     link = data.posts[i].post_url; 

    if("photo" == type) { 
     if(data.posts[i].hasOwnProperty("alt_sizes") { 
      var photourl = results.response.posts[i].photos[i].alt_sizes[i].url; 
      $("#tumoffers").append("<div class='tumpost'><a href='" + link + "'><img src='" + photourl + "' alt='" + title + "'/></a></div>"); 
     } 
    } 
    i++; 
} 
相关问题