Here is my code for call API using Fetch URL method, after getting data from api how to display data into HTML table
index.html
<body>
<input type="text" name="daterange" value="" />
<script>
$(function () {
$('input[name="daterange"]').daterangepicker({
opens: 'left'
}, function (start, end, label) {
variable_one = "selected_date: " start.format('YYYY-MM-DD');
console.log("Hai hari its working");
console.log(variable_one);
fetch("http://localhost:3000/09-12-2021")
.then(response => response.json())
.then(data => console.log(data));
});
});
</script>
</body>
db.json
Here is my sample json data
[
{
"s.no": 1,
"date": "09-12-2021",
"time": "12am",
"videos": "video_01",
"button": "play"
}]
How to display data into HTML table
CodePudding user response:
Using different Object method in js like Object.keys
and Object.values
... you can cycle throgh each values or keys of the object you get from the data array ! ... using this with the power of template strings and DOM manipulation u can achieve what you are looking for .
Example =>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>Table</title>
</head>
<body>
<table border="1">
<thead>
<tr></tr>
</thead>
<tbody></tbody>
</table>
<script type="text/javascript" charset="utf-8">
const thead = document.querySelector("table > thead > tr");
const tbody = document.querySelector("table > tbody");
let data = [{
"s.no": 1,
"date": "09-12-2021",
"time": "12am",
"videos": "video_01",
"button": "play"
}];
Object.keys(data[0]).forEach(attr => {
thead.innerHTML =
`<th>${attr}</th>`;
});
data.forEach(ele =>{
let append = "";
append = "<tr>";
Object.values(ele).forEach(entry =>{
append = `<td>${entry}</td>`;
});
append = "</tr>";
tbody.innerHTML = append;
});
</script>
</body>
</html>