2013-09-25 104 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++; 
} 
相關問題