1

I have a JSON Like below:

  {"sessions":[
    {
        "totalusers":"2",
        "Users": [
            { "id": 1, "name": "abc" },
            { "id": 2, "name": "def" }
        ]
    }
  ]}

I have my HTML as below

     <div>
        <p class="totalusers">Total Users</p>
        <p class="Users">Users</p>
     </div>

My Jquery

  $.getJSON("sample.json",  function(data) {
  $(".totalusers").append(data.sessions[0].totalusers); 
  $(".Users").append(data.sessions[0].Users.id[]);
 }  );

I would like all my users in the JSON to be shown in a list in the HTML. Please help. I am missing something in the jQuery "data.sessions[0].Users.id[]" to show the whole list.

4

2 回答 2

2

Praveen's answer is in the right direction but he is not using $.each correctly. You will need to use $.each to iterate over each of the users.

$.getJSON("sample.json",  function(data) {
  $(".totalusers").append(data.sessions[0].totalusers); 
  $.each(data.sessions[0].Users, function(i, value){
    $(".Users").append(value.id);
  })
});

I would also recommend changing your HTML to use an actual list like

<div>
    <p class="totalusers">Total Users</p>
    <p class="Users">Users</p>
    <ul class="users-list"></ul>
 </div>

Then your JS would be:

$.getJSON("sample.json",  function(data) {
  $(".totalusers").append(data.sessions[0].totalusers); 
  $.each(data.sessions[0].Users, function(i, value){
    $(".users-list").append('<li>' + value.id + '</li>');
  })
});
于 2013-06-10T17:34:16.013 回答
1

What you need is $.each() function.

$.getJSON("sample.json",  function(data) {
  $(".totalusers").append(data.sessions[0].totalusers);
  var $Users = $(".Users");
  $.each(data.sessions[0].Users, function(i, value){
    $Users.append(value.id);
  });
});
于 2013-06-10T17:30:21.877 回答