简体   繁体   English

使用JQuery将数据附加到表

[英]Append data to table using JQuery

How to append json data in table. 如何在表中附加json数据。 Json data format {"FirstName":"Cho" ,"LastName":"Chee","Company":"solution"} . Json数据格式{"FirstName":"Cho" ,"LastName":"Chee","Company":"solution"} This code did not show data in table as expected. 此代码未按预期在表中显示数据。

JQuery Code: 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 : 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>

Take a look at below code snippet. 看看下面的代码片段。 I am assuming you will get array of data from your server. 我假设您将从服务器上获取数据数组。

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

What you need to add are whole table rows with table data cells for each item property. 您需要添加的是整个表行以及每个项目属性的表数据单元。 Additionally you want to add this to the table body not to the table as a whole. 另外,您想将此添加到表主体而不是整个表。 I would do it like this: 我会这样做:

HTML: 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: 使用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>';
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM