有人可以解释为什么这只返回1个结果(应该是4个)。它仅返回最新的帖子标题,在这里我想获得类别(ID:121)中的所有帖子标题,在本例中为四个。

<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>

最佳答案

您遇到的问题是您没有遍历所有类别,而是仅使用与posts数组相同的索引进行引用。您应该像这样遍历所有类别

var postCategories= post.categories;

for (var postCategoryIndex in postCategories)
{
    var postCategory = postCategories[postCategoryIndex].id;
    if (postCategory == '121') {
      $("#post").append(postTitle + "<br />").trigger('create');
    }
}

关于javascript - JSON循环只有1个结果,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27867307/

10-14 03:11