2015-01-09 2 views
0

누군가 1 개의 결과 만 반환하는 방법을 설명 할 수 있습니까 (4 개가 있어야 함). 그것만이 가장 최근의 게시물 제목을 돌려 주며,이 경우에는 4 개의 카테고리 (ID : 121)에있는 모든 게시물 제목을 얻고 싶습니다.JSON 루프의 결과 1 개만

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

JSON이 어떻게 생겼는지 추측해야합니까? – Teemu

+0

해결책이 아니라 호기심. 'for' 루프가'i! = response.posts.length'를하는 이유는 무엇입니까? 나는 항상 'i

+4

@Teemu 링크를 따라 가면 json이 어떻게 보이는지 알고 싶지 않을 것입니다 ... –

답변

1

당신이 가진 문제는 당신 대신 당신이 당신의 게시물 배열과 같은 인덱스를 참조하고, 모든 범주를 반복하지 않는 것입니다. 당신은 JSON이하는 실제로 49 개 게시물을 포함 반환이

var postCategories= post.categories; 

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

처럼 모든 카테고리를 통해 반복해야하고, 당신은 당신이 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'); 
    }); 
}