admin管理员组

文章数量:1417055

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?

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

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?

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);
}
});
Share Improve this question edited Jan 14, 2019 at 2:23 Jack Bashford 44.2k11 gold badges55 silver badges82 bronze badges asked Jan 14, 2019 at 2:19 FrinkFrink 871 silver badge8 bronze badges 8
  • This is quite broad. You'd benefit from constraining it more and posting what you've tried already. – Chris Farmer Commented Jan 14, 2019 at 2:21
  • Please add your current jQuery code to the question. – Jack Bashford Commented Jan 14, 2019 at 2:22
  • I've looked around a bit, but all the examples I have found required Jquery, I'll post my current solution. – Frink Commented Jan 14, 2019 at 2:22
  • Yes @Frink, then we can help fix your problem. – Jack Bashford Commented Jan 14, 2019 at 2:22
  • So you really just need to convert the ajax-based data retrieval into "plain" javascript? Just curious, why not use jquery? It's certainly easier than rolling your own. – Chris Farmer Commented Jan 14, 2019 at 2:31
 |  Show 3 more ments

2 Answers 2

Reset to default 4

If we do it the modern way, it is not that much code. This will work in Chrome / FF and any other modern browser. Note, that I fake-load JSON in Fetch API Promise's catch clause for demo purposes, you should obviously remove it in your code.

Once you grasp how you can use map() and reduce() to manipulate collections of data, it will simplify the code a lot.

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

本文标签: jqueryCreate a Table using JSON data from an API using Pure JavascriptStack Overflow