简体   繁体   中英

Generate Dynamic HTML Table From Javascript Array

I am currently making a web app with php, javascript, and html. I make a post http call to php to grab information from my database that I have to display in an html table. I get the following data back from my post http call:

0:
DwgFile: "\\TEAM\wwwroot\dwfs\A-104589 ELEVATOR FRAME ASS'Y.idw.dwf"
DwgNo: "2A"
IssueDate: "2020-05-30"
IssueEMID: 10709
ItemID: 232002
ItemNo: "A-104589"
OrderID: 13352
Qty Total: 1
ShortDesc: "ELEVATOR FRAME ASS'Y"
SolidFile: "\\TEAM\wwwroot\dwfs\A-104589 ELEVATOR FRAME ASS'Y.iam.dwf"
_DwgNo: 2
__proto__: Object
1:
DwgFile: "\\TEAM\wwwroot\dwfs\A-104599 DRIVE SHAFT ASS'Y.idw.dwf"
DwgNo: "3A"
IssueDate: "2019-12-12"
IssueEMID: 10710
ItemID: 232012
ItemNo: "A-104599"
OrderID: 13352
Qty Total: 1
ShortDesc: "DRIVE SHAFT ASS'Y"
SolidFile: "\\TEAM\wwwroot\dwfs\A-104599 DRIVE SHAFT ASS'Y.iam.dwf"
_DwgNo: 3

How can I display each of these indexes in the array in a row in an html table. Each attribute in the array will be a column within the table. I need the table to be dynamic as the number of indexes in the array will change depending on the user's input. Any help is much appreciated. Cheers!

EDIT This is what the table should look similar to在此处输入图像描述

First, create an empty table using HTML.

<table id="dynamic_table"></table>

Next, we can fill the table using jQuery.

var data_from_post = ...

//create head by looping through keys of first object in result
var table_head = $('<tr></tr>').wrap('<thead></thead>');
$.each(data_from_post[0], function(key) {
  table_head.append('<th>' + key + '</th>');
});

//create body by looping through each result, then looping through each key in that result
var table_body = $('<tbody></tbody>');
$.each(data_from_post, function(index, values) {
    var row = $('<tr></tr>');
    $.each(values, function(key, value) {

        //here you can perform changes to the 'value' variable if you need it to be different in the table
        //for example, wrap the `_DwgNo` with a button
        if(key == '_DwgNo') {
            value = '<button>' + value + '</button>'
        }

        row.append('<td>' + value + '</td>');
    });
    table_body.append(row);
});

//add the head and body to the table
$('#dynamic_table').append(table_head).append(table_body);

Here is a jsfiddle containing this solution

https://jsfiddle.net/2Lon5vj3/1/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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