使用JQuery将数据附加到表

时间:2015-10-16 08:35:59

标签: javascript jquery json

如何在表格中附加json数据。 Json数据格式{"FirstName":"Cho" ,"LastName":"Chee","Company":"solution"}。此代码未按预期显示表中的数据。

JQuery代码:

var uri = 'api/Employee/GetData';
$(document).ready(function () {
$.getJSON(uri)
    .done(function (data) {
        $.each(data, function (key, item) {
            $('<li>', { text: formatItem(item) }).appendTo($("#tbdata"));
        });
    });
});

function formatItem(item) {
return item.FirstName + '  ' + item.LastName + ' ' + item.Company;
}

HTML表格:

<table class="table-bordered table-striped table table-hover" id="tbdata">
  <tr>
    <th>First Name</th>
    <th>Last Name</th>
    <th>Company</th>
   </tr>
  </table>

2 个答案:

答案 0 :(得分:1)

看一下下面的代码片段。我假设您将从服务器获取数据数组。

&#13;
&#13;
function formatItem(item) {
return '<td>'+item.FirstName + '</td> <td> ' + item.LastName + ' </td><td>' + item.Company+'</td>';
}

var data = [
{"FirstName":"Cho","LastName":"Chee","Company":"solution"},
{"FirstName":"Cho1","LastName":"Chee1","Company":"solution1"},
{"FirstName":"Cho2","LastName":"Chee2","Company":"solution2"},
];

$.each(data, function (key, item) {

            $('<tr>', { html: formatItem(item) }).appendTo($("#tbdata"));
        });
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<table class="table-bordered table-striped table table-hover" id="tbdata">
  <tr>
    <th>First Name</th>
    <th>Last Name</th>
    <th>Company</th>
   </tr>
  </table>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

您需要添加的是具有每个项属性的表数据单元格的整个表行。此外,您希望将此添加到表体,而不是作为整体添加到表。我会这样做:

HTML:

<table class="table-bordered table-striped table table-hover">
<thead>  
    <tr>
        <th>First Name</th>
        <th>Last Name</th>
        <th>Company</th>
    </tr>
</thead>
<tbody id="tbdata">
<!-- data will go here -->
</tbody>
</table>

使用Javascript:

$(document).ready(function () {
$.getJSON(uri)
    .done(function (data) {
        var html = "";
        $.each(data, function (key, item) {
            html += formatItem(item); 
        });
        $("#tbdata").append(html);
    });
});
function formatItem(item) {
    return '<tr><td>' item.FirstName + '</td><td>' + item.LastName + '</td><td>' + item.Company + '</td></tr>';
}