Problem filling HTML table

Asked

Viewed 31 times

0

I’m trying to load an HTML table with data from a Sqlserver BD. I am able to recover the data from the BD, the problem is time to load the table, which is filling with the names of the columns and not with the values. I’m unable to identify the error in the code, I wish someone could point me to where I’m going wrong.

Excerpt from Javascript:

function loadData() {
    tableBody = document.querySelector("#modelTable > tbody");

    const request = new XMLHttpRequest();  
    request.open("get", "http://localhost:52691//api/AppLock/run/all");

    request.onload = () => {
        const json = JSON.parse(request.responseText);
        populateTable(json);
    };

    request.send();

}

function populateTable(json) {
    console.log(json);
    // Clears out existing table data
    while (tableBody.firstChild) {
        tableBody.removeChild(tableBody.firstChild);
    }

    // Populate table
    json.forEach((row) => {
        console.log(row);
        const tr = document.createElement("tr");

        Object.keys(row).forEach((cell) => {
            console.log(cell);
            const td = document.createElement("td");
            td.textContent = cell;
            tr.appendChild(td);
        });

        tableBody.appendChild(tr);
    });
}

Example of JSON:

inserir a descrição da imagem aqui

The table is appearing this way:

inserir a descrição da imagem aqui

  • Could send full JSON code?

  • @Maury Developer just edited the question

1 answer

2


The value of cell in the forEach of Object.keys(row) returns only the object’s key names. To get the values of each key you need to use the key bracketed notation in cell of the variable row:

td.textContent = row[cell];
  • 1

    Problem solved. Thank you.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.