2015-06-08 7 views
0

main.php JQuery код:Как пропустить этот объект JSON?

$.getJSON('posts.php',function(data){ 
    data.posts.forEach(function(post){ 
     // set variables and append divs to document 
    }) 
    data.comments.forEach(function(post){ 
     // set variables and append divs to document 
    }) 
}) 

(Старый - Работает с текущим кодом JQuery)

Пример объекта, содержащего 2 сообщения и 3 комментариев. Сообщение с id: 5 имеет 1 комментарий и сообщение id: 2 имеет 2 комментария.

// the two posts ID: 5 and 2 

{"posts":[{ 
    "id":"5", 
    "image":"link.jpg", 
    "submitter":"4322309", 
    "views":"3" 
}, 
{ 
    "id":"2", 
    "image":"link.jpg", 
    "submitter":"4322309", 
    "views":"10" 
}], 

// now each comment tied to the posts 

"comments":[ 
{ 
    "id":"1", 
    "submitter":"submitter", 
    "time":"2435657", 
    "comment":"comment", 
    "score":"10", 
    "postid":"2" 
}, 
{ 
    "id":"2", 
    "submitter":"submitter", 
    "time":"2435657", 
    "comment":"comment", 
    "score":"10", 
    "postid":"2" 
}, 
{ 
    "id":"3", 
    "submitter":"submitter", 
    "time":"2435657", 
    "comment":"comment", 
    "score":"10", 
    "postid":"5" 
}]} 

(NEW - Не работает с текущим кодом JQuery)

Пример объекта, содержащего 2 сообщения и 3 комментариев. Сообщение с id: 5 имеет 1 комментарий и сообщение id: 2 имеет 2 комментария.

// the two posts ID: 5 and 2 

{ 
    "posts":{ 
     "5": { 
      "id":"5", 
      "image":"link.jpg", 
      "submitter":"4322309", 
      "views":"3" 
     }, 
     "2": { 
      "id":"2", 
      "image":"link.jpg", 
      "submitter":"4322309", 
      "views":"5" 
     } 
    }, 

    // now each comment tied to the posts 
    "comments":{ 
     "2": [{ 
      "id":"1", 
      "submitter":"submitter", 
      "time":"2435657", 
      "comment":"comment", 
      "score":"10", 
      "postid":"2" 
     }, 
     { 
      "id":"2", 
      "submitter":"submitter", 
      "time":"2435657", 
      "comment":"comment", 
      "score":"10", 
      "postid":"2" 
     } 
    ], 
     "5": [{ 
      "id":"3", 
      "submitter":"submitter", 
      "time":"2435657", 
      "comment":"comment", 
      "score":"10", 
      "postid":"5" 
     }] 
    } 
} 

Я не уверен, как использовать этот объект JSON в этом новом сценарии.

В принципе, как я прокручиваю этот новый?

+0

Переместить петлю комментарии внутри цикла сообщений. – royhowie

+0

Возможный дубликат [Loop через объект JavaScript] (http://stackoverflow.com/questions/684672/loop-through-javascript-object) –

+0

Можете ли вы разместить _set переменные, добавить divs_ part здесь? –

ответ

0

Первый вариант (ваниль JS):

var postObj; 
for (var id in data.posts) { 
    postObj = data.posts[id]; 
    // do your thing 
} 

var commentList; 
for (var id in data.comments) { 
    commentList = data.comments[id]; 
    commentList.forEach(function(comment) { 
    // do your thing 
    }); 
} 

Для получения дополнительной информации о ... в петлях https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in


Второй вариант (Jquery):

$.each(data.posts, function(id, post) { 
    // do your thing 
}); 

$.each(data.comments, function(id, commentList) { 
    $.each(commentList, function(index, comment) { 
    // do your thing. you could also use the forEach loop if you want 
    }); 
}); 

Для получения дополнительной информации о $ .each http://api.jquery.com/jquery.each/

2

Вы можете легко перебирать, как это: -

$.each(data['posts'], function(outerKey, idVal) { //outerKyeas are 2, 5 
    $.each(idVal, function(innerKey, val) { // innerKeys are id,submitter etc 
    console.log(innerKey, val); 
    }); 
}); 

Комментарии может быть петельные через, как точно так же.

0

Try $ .each в сочетании с базовым 'для (вар пост в data.posts)' петля:

var data = { 
 
    "posts": { 
 
    "5": { 
 
     "id": "5", 
 
     "image": "link.jpg", 
 
     "submitter": "4322309", 
 
     "views": "3" 
 
    }, 
 
    "2": { 
 
     "id": "2", 
 
     "image": "link.jpg", 
 
     "submitter": "4322309", 
 
     "views": "5" 
 
    } 
 
    }, 
 

 
    // now each comment tied to the posts 
 
    "comments": { 
 
    "2": [{ 
 
     "id": "1", 
 
     "submitter": "submitter", 
 
     "time": "2435657", 
 
     "comment": "comment", 
 
     "score": "10", 
 
     "postid": "2" 
 
    }, { 
 
     "id": "2", 
 
     "submitter": "submitter", 
 
     "time": "2435657", 
 
     "comment": "comment", 
 
     "score": "10", 
 
     "postid": "2" 
 
    }], 
 
    "5": [{ 
 
     "id": "3", 
 
     "submitter": "submitter", 
 
     "time": "2435657", 
 
     "comment": "comment", 
 
     "score": "10", 
 
     "postid": "5" 
 
    }] 
 
    } 
 
}; 
 

 

 
for (var post in data.posts) { 
 
    $.each(data.comments[data.posts[post].id], function() { 
 
    alert("Post: " + data.posts[post].id + ", Comment ID: " + this.id + ', Comment Text: "' + this.comment + '"') 
 
    }); 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

0

Ну я говорю, вам нужно 3 петли здесь, чтобы принести каждый comment объект как

DEMO

$(data.comments).each(function(index,commentArray){ 
    $.each(commentArray,function(index,value){ 
     $.each(value,function(index1,value1){ 
      console.log(value1); 
     }); 
    }); 
}); 

для Post вы можете получить его с одной петлей

$.each(data.posts,function(index,post){ 
     console.log(post); 
}); 
Смежные вопросы