有人可以解释为什么这只会返回1个结果(应该有4个)。它只返回最近的帖子标题,我希望获得该类别中的所有帖子标题(ID:121),在这种情况下为4。
<script type="text/javascript">
var posturl = "http://www.tropical420.com/api/get_posts/?posts_per_page=-1";
$.ajax({
type: 'GET',
url: posturl,
complete: function(){
},
success: function (data) {
var response = data; //JSON.parse(data);
//loop through posts
for(var i = 0; i != response.posts.length; i++) {
//get each element in the array
var post = response.posts[i];
// post vars
var postTitle = post.title;
var postContent = post.content;
var postCategory = post.categories[i].id;
// output stuff so we can see things
if (postCategory == '121') {
$("#post").append(postTitle + "<br />").trigger('create');
}
}
},
error:function (xhr, ajaxOptions, thrownError) {
alert("Error");
}
});
</script>
<div id="post"></div>
答案 0 :(得分:1)
您遇到的问题是您没有遍历所有类别,而只是使用与您的posts数组相同的索引。你应该像这样迭代所有的类别
var postCategories= post.categories;
for (var postCategoryIndex in postCategories)
{
var postCategory = postCategories[postCategoryIndex].id;
if (postCategory == '121') {
$("#post").append(postTitle + "<br />").trigger('create');
}
}
答案 1 :(得分:1)
返回的JSON确实包含49个帖子,你知道如果你尝试过console.log(response.posts.length)
sanfor已经指出了代码中的逻辑错误,但是整个回调函数可以更清晰地编写,如下所示:
function (data) {
data.posts.filter(function (post) {
return post.categories.filter(function (cat) { return cat.id === '121'; });
}).forEach(function (post) {
$("#post").append(post.title + "<br />").trigger('create');
});
}