Tumblr API 收到“未捕获的类型错误:无法读取未定义的属性”类型”

Tumblr API getting 'Uncaught TypeError: Cannot read property 'type' of undefined'

本文关键字:类型 读取 未定义 API 属性 错误 收到 Tumblr      更新时间:2023-09-26

我的网站上有一系列的Tumblr提要,每个提要都从不同的标签中检索帖子。

第一个提要脚本有效,但第二个和第三个脚本抛出错误:

Uncaught TypeError: Cannot read property 'type' of undefined

每个脚本对标记检索和追加到的数据的元素的接受完全相同。

我很难弄清楚这一点。有谁知道我做错了什么?

$.ajax({
    url: "http://api.tumblr.com/v2/blog/myblog.tumblr.com/posts?api_key=mykey&tag=news",
    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 == "text") {
         var title = results.response.posts[i].title;
         var content = results.response.posts[i].body;
         $("#tumnews #newscara").append("<div class='tumpost'><a href='" + link + "'><h2>" + title + "</h2>" + content + "</a></div>");
       }
       else if (type == "photo") {
         var photourl = results.response.posts[i].photos[0].alt_sizes[0].url;
         $("#tumnews #newscara").append("<li><div class='tumpost'><a href='" + link + "'><img src='" + photourl + "' alt='" + title + "'/></a></div></li>");
       }
      i++;
     }//END WHILE

  $("#newscara").flexisel({
    visibleItems: 5,
    animationSpeed: 200,
    autoPlay: true,
    autoPlaySpeed: 3000,
    pauseOnHover: true,
    clone:false,
  });
    }//END RESULTS FUNCTION
});

我发现错误是因为我要检索的其他两个标签中的帖子较少,并且因为我指定了它while (i < 10)它不断循环,如果少于 10 个帖子,则会出现错误。

我通过将 while 语句替换为

while (i < results.response.posts.length)

因此,它只会循环浏览实际存在的帖子数量。

相关文章: