abcid d
abcid d

Reputation: 2963

Load External Json to HTML Table

I have an external Json named members.json. I like to load the data to HTML table from the Json file by using Jquery, but somehow it doesn't work.

Please help.

Json

{"data":
    [
        {
            name: "Keely Luther",
            email: "[email protected]",
            phone: "617 465 6314",
            id  : "1235-454676",
            plan : "Plan A",
            type : "New Medic",
            group : "ABC-1",
            status: "Approved"
        },
        {
            name: "Mike Jenson",
            email: "[email protected]",
            phone: "943 355 0193",
            id  : "1235-478948",
            plan : "Plan A",
            type : "New Medic",
            group : "ABC-1",
            status: "Cancelled"
        }
    ]
}

.JS

$(document).ready( function() {  
$.getJSON('members.json',
  function(data) {        
    $("#Table").html(" FirstLastMiddle");
    for (var i = 0; i < data.length; i++)
        {
            var tr="";
              var td1=""+data[i]["name"]+"";
              var td2=""+data[i]["email"]+"";
              var td3=""+data[i]["phone"]+"";
              var td4=""+data[i]["id"]+"";

            $("#Table").append(tr+td1+td2+td3+td4);

        }
  });
});

HTML

<table id="Table" width="90%" border="1" bordercolor="#ccc">

Upvotes: 1

Views: 1584

Answers (2)

user9227272
user9227272

Reputation: 11

Here's one way of doing it.

$(function () {

$.getJSON('members.json', function(data) {        
    var table = $("#Table").empty();
    $.each(data, function (i, member) {
        $("<tr>", {
            html: [
                $("<td>", { html: member.name }),
                $("<td>", { html: member.email }),
                $("<td>", { html: member.phone }),
                $("<td>", { html: member.id })
            ],
            appendTo: table
        });
    });
});

});

Upvotes: 1

Bryan Dellinger
Bryan Dellinger

Reputation: 5304

need to add the html tags to your append

var data = [{
    name: "Keely Luther",
    email: "[email protected]",
    phone: "617 465 6314",
    id: "1235-454676",
    plan: "Plan A",
    type: "New Medic",
    group: "ABC-1",
    status: "Approved"
  },
  {
    name: "Mike Jenson",
    email: "[email protected]",
    phone: "943 355 0193",
    id: "1235-478948",
    plan: "Plan A",
    type: "New Medic",
    group: "ABC-1",
    status: "Cancelled"
  }
];


$(document).ready(function() {
  $.each(data, function(i, obj) {
    $("#Table").append(
      '<tr><td>' + obj.name + '</td><td>' + obj.email + '</td><td>' + obj.phone + '</td><td>' + obj.id + '</td></tr>');
  })
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="Table" width="90%" border="1" bordercolor="#ccc">

Upvotes: 0

Related Questions