Load External Json to HTML Table

大憨熊 提交于 2021-02-08 08:49:28

问题


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: "kluther@abc.com",
            phone: "617 465 6314",
            id  : "1235-454676",
            plan : "Plan A",
            type : "New Medic",
            group : "ABC-1",
            status: "Approved"
        },
        {
            name: "Mike Jenson",
            email: "mike_j@yahoo.com",
            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">

回答1:


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
        });
    });
});

});



回答2:


need to add the html tags to your append

var data = [{
    name: "Keely Luther",
    email: "kluther@abc.com",
    phone: "617 465 6314",
    id: "1235-454676",
    plan: "Plan A",
    type: "New Medic",
    group: "ABC-1",
    status: "Approved"
  },
  {
    name: "Mike Jenson",
    email: "mike_j@yahoo.com",
    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">


来源:https://stackoverflow.com/questions/48292679/load-external-json-to-html-table

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!