This is my code and I am trying to pull in JSON data from an API.
The data is being successfully pulled but it is not coming in table format. It is coming as a continuous horizontal string.
if (this.readyState == 4 && this.status == 200) {
// Typical action to be performed when the document is ready:
var respoTxt = xhttp.responseText;
var myObj = JSON.parse(respoTxt);
document.getElementById("demo").innerHTML = '<table><tr><thead>' +
myObj["dataset"]["column_names"][5] + '</thead><thead>' + myObj["dataset"]
["column_names"][6] + '</thead></tr>';
myObj["dataset"]["data"].forEach(function(p, i) {
//Below is 1st code version:
// var tr = document.createElement("tr");
// document.getElementById("demo").appendChild(tr);
// var td1 = document.createElement("td");
// tr.appendChild(td1);
// var td2 = document.createElement("td");
// tr.appendChild(td2);
// td1.innerHTML = myObj["dataset"]["data"][i][5];
// td2.innerHTML = myObj["dataset"]["data"][i][6];
document.getElementById("demo").innerHTML += '<tr>';
document.getElementById("demo").innerHTML += '<td>' + myObj["dataset"]
["data"][i][5] + '</td>';
document.getElementById("demo").innerHTML += '<td>' + myObj["dataset"]
["data"][i][6] + '</td>';
document.getElementById("demo").innerHTML += '</tr>';
//Here's the 3rd code version:
// document.getElementById("demo").innerHTML += '<tr><td>' +
myObj["dataset"]["data"][i][5] + '</td><td>' + myObj["dataset"]["data"][i]
[6] + '</td></tr>';
});
document.getElementById("demo").innerHTML += '</table>';
}
I have used 3 different types of code inside (2 of them marked in comments above and below the active one).
None of them are showing the data in table format.
Here's the Codepen.
innerHTML, add them to a temporary string, then assign that toinnerHTMLat the end.var html = '<table><tr><thead>'before the loop, thenhtml += '<td> + ... </td>';inside the loop, then finally.innerHTML = html;at the end.