简体   繁体   English

使用纯Javascript从API使用JSON数据创建表

[英]Create a Table using JSON data from an API using Pure Javascript

I am currently using Jquery to populate a table with data from an API, but I want to do it without requiring any external libraries, is there a way to do this using pure javascript? 我目前正在使用Jquery用来自API的数据填充表,但是我想做到这一点而无需任何外部库,有没有办法使用纯JavaScript来做到这一点?

I currently use the following solution: 我目前使用以下解决方案:

$.ajax({
url: 'http://localhost:2672/api/notes',
type: 'GET',
success: function (myNotes) {
    console.log(myNotes)
    // EXTRACT VALUE FOR HTML HEADER. 
    var col = [];
    for (var i = 0; i < myNotes.length; i++) {
        for (var key in myNotes[i]) {
            if (col.indexOf(key) === -1 && (key === 'title' || key === 'content' || key == 'category')) {
                col.push(key);
            }
        }
    }

    // CREATE DYNAMIC TABLE.
    var table = document.createElement("table");

    // CREATE HTML TABLE HEADER ROW USING THE EXTRACTED HEADERS ABOVE.

    var tr = table.insertRow(-1); // TABLE ROW.

    for (var i = 0; i < col.length; i++) {
        var th = document.createElement("th"); // TABLE HEADER.
        th.innerHTML = col[i];
        tr.appendChild(th);
    }

    // ADD JSON DATA TO THE TABLE AS ROWS.
    for (var i = 0; i < myNotes.length; i++) {

        tr = table.insertRow(-1);

        for (var j = 0; j < col.length; j++) {
            var tabCell = tr.insertCell(-1);
            tabCell.innerHTML = myNotes[i][col[j]];
        }
    }

    // FINALLY ADD THE NEWLY CREATED TABLE WITH JSON DATA TO A CONTAINER.
    var divContainer = document.getElementById("showNotes");
    divContainer.innerHTML = "";
    divContainer.appendChild(table);
}
});

If we do it the modern way, it is not that much code. 如果我们以现代方式进行操作,那么代码就不多了。 This will work in Chrome / FF and any other modern browser. 这将在Chrome / FF和其他任何现代浏览器中运行。 Note, that I fake-load JSON in Fetch API Promise's catch clause for demo purposes, you should obviously remove it in your code. 请注意,出于演示目的,我在Fetch API Promise的catch子句中伪装了JSON,显然您应该在代码中将其删除。

Once you grasp how you can use map() and reduce() to manipulate collections of data, it will simplify the code a lot. 一旦掌握了如何使用map()reduce()来操纵数据集合,它将大大简化代码。

The code below can be much shorter, but I wanted to provide some readability. 下面的代码可以短得多,但是我想提供一些可读性。

 const wrapper = document.getElementById('content'); const demoData = [ {"id":1, "name":"John", "age":21}, {"id":2, "name":"Bob", "age":19}, {"id":3, "name":"Jessica", "age":20} ]; function fetchData() { fetch("data.json") .then(data => data.json()) .then(jsonData => populate(jsonData)) .catch(e => { wrapper.innerText = "Error: "+e+" going to use demo data"; populate(demoData); //remove me }); }; document.addEventListener('DOMContentLoaded', fetchData, false); function dom(tag, text) { let r = document.createElement(tag); if (text) r.innerText = text; return r; }; function append(parent, child) { parent.appendChild(child); return parent; }; function populate(json) { if (json.length === 0) return; let keys = Object.keys(json[0]); let table = dom('table'); //header append(table, keys.map(k => dom('th', k)).reduce(append, dom('tr')) ); //values const makeRow = (acc, row) => append(acc, keys.map(k => dom('td', row[k])).reduce(append, dom('tr')) ); json.reduce(makeRow, table); wrapper.appendChild(table); }; 
 <!DOCTYPE html> <html> <body> <div id="content"></div> </body> </html> 

You can do something like this 你可以做这样的事情

 success: function (myNotes) { var cols = Object.keys(myNotes[0]); var headerRow = ''; var bodyRows = ''; cols.map(function(col) { headerRow += '<th scope="col">' + col + '</th>'; }); myNotes.map(function(row) { bodyRows += '<tr>'; cols.map(function(colName) { bodyRows += '<td>' + row[colName] + '<td>'; }); bodyRows += '</tr>'; }); return '<table class="table table-striped table-dark"' +'><thead><tr>' +headerRow +'</tr></thead><tbody>' +bodyRows +'</tbody></table>'; } 

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

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