這是我使用 Fetch URL 方法呼叫 API 的代碼,從 api 獲取資料后如何將資料顯示到 HTML 表中
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
這是我的示例 json 資料
[
{
"s.no": 1,
"date": "09-12-2021",
"time": "12am",
"videos": "video_01",
"button": "play"
}]
如何將資料顯示到 HTML 表格中
uj5u.com熱心網友回復:
在 js 中使用不同的 Object 方法,例如Object.keys和Object.values...您可以回圈遍歷從資料陣列中獲得的物件的每個值或鍵!...使用模板字串和 DOM 操作的強大功能,您可以實作您正在尋找的東西。
示例 =>
<!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>
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/389624.html
標籤:javascript html json 接口 拿来
