我无法从我的 tumblr 中提取格式为 JSON 的内容。我从 tumblr 注册了一个 API key ,并拥有正确的 API 链接,但我在 $.getJSON 中丢失了一些东西。下面我将展示我的 JSON 和 jQuery 的样子。
这是我的 JSON 的样子:
{
"meta": {
"status": 200,
"msg": "OK"
},
"response": {
"blog": {
"title": "BLOG TITLE",
"name": "BLOG NAME",
"posts": 96,
"url": "http://BLOGTITLE.tumblr.com/",
"updated": 1370605005,
"description": "BLOG DESCRIPTION",
"ask": false,
"ask_anon": false,
"is_nsfw": false,
"share_likes": true,
"likes": 0
},
"posts": [
{
"blog_name": "BLOG NAME",
"id": 52373434879,
"post_url": "POST URL",
"slug": "POST SLUG",
"type": "photo",
"date": "2013-03-07 11:36:44 GMT",
"timestamp": 1370605004,
"state": "published",
"format": "html",
"reblog_key": "T0m0e51u",
"tags": [],
"short_url": "SHORT URL",
"highlighted": [],
"note_count": 1,
"caption": "PHOTO CAPTION TEXT DESCRIPTION",
"image_permalink": "http://BLOGTITLE.tumblr.com/image/52373434879",
"photos": [
{
"caption": "",
"alt_sizes": [
{
"width": 640,
"height": 960,
"url": "http://31.media.tumblr.com/.../...jpg"
},
{
"width": 500,
"height": 750,
"url": "http://31.media.tumblr.com/.../..._500.jpg"
},
{
"width": 400,
"height": 600,
"url": "http://24.media.tumblr.com/.../..._400.jpg"
},
{
"width": 250,
"height": 375,
"url": "http://31.media.tumblr.com/.../..._250.jpg"
},
{
"width": 100,
"height": 150,
"url": "http://24.media.tumblr.com/.../..._100.jpg"
},
{
"width": 75,
"height": 75,
"url": "http://24.media.tumblr.com/.../..._75sq.jpg"
}
],
"original_size": {
"width": 640,
"height": 960,
"url": "http://31.media.tumblr.com/.../..._1280.jpg"
}
}
]
},
这是我的 jQuery 的样子:
jQuery(document).ready(function(){
var url = "http://api.tumblr.com/v2/blog/BLOGNAME.tumblr.com/posts?api_key=APIKEY&limit=5";
var src;
var caption;
$.getJSON(url, function(results){
$.each(results.response, function(i,item){
src = "posts.photos.alt_sizes.url";
caption = posts.caption;
$("<img/>").attr("src", src).appendTo("#submissions").wrap('<div class="postImage"></div>').after('<span class="postCaption">' + caption + '</div>');
});
HTML:
<div id="submissions"></div>
我很漂亮确定问题出在 $.getJSON 或 $.each 中,但我无法弄清楚到底是什么。有帮助吗?
谢谢。
最佳答案
您可能会遇到错误,因为您正在尝试访问 undefined variable post
。您正在遍历 results.response
,但看起来您想遍历 results.response.posts
,这是一个博客文章数组。
此外,每个帖子似乎都有一个照片
数组,您必须从中选择您想要的照片尺寸的元素。
例子:
$.each(results.response.posts, function(i, item){
var src = item.photos[0].alt_sizes[0].url; // first picture, first size
var caption = item.caption;
$("<img/>").attr("src", src).appendTo("#submissions").wrap('<div class="postImage"></div>').after('<span class="postCaption">' + caption + '</div>');
});
当然,如果帖子没有照片且数组为空,您将遇到运行时错误,但我假设您会考虑到这些情况。
另一个问题是您不能向 tumblr API 发出 Ajax 请求,因为它是一个外部域。但是,tumblr API 支持 JSONP,因此如果您将 &callback=?
添加到 URL,则告诉 jQuery 使用 JSONP:
var url = "[...]/posts?api_key=APIKEY&limit=5&callback=?";
我建议阅读一些基本的 JavaScript 教程,以了解如何使用数组和对象:
关于javascript - 使用 tumblr API (JSON) 和 $.getJSON 从我的 tumblr 博客中获取最新的帖子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18447503/