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

时间:2019-01-14 02:19:33

标签: javascript jquery api

我目前正在使用Jquery用来自API的数据填充表,但是我想做到这一点而无需任何外部库,有没有办法使用纯JavaScript来做到这一点?

我目前使用以下解决方案:

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

2 个答案:

答案 0 :(得分:2)

如果我们以现代方式进行操作,则不需要太多代码。这将在Chrome / FF和其他任何现代浏览器中运行。请注意,出于演示目的,我在Fetch API Promise的catch子句中伪装了JSON,显然您应该在代码中将其删除。

一旦您掌握了如何使用map()reduce()来操纵数据集合,它将大大简化代码。

下面的代码可以短很多,但是我想提供一些可读性。

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>

答案 1 :(得分:0)

您可以这样做

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