|
 |
|
สอบถามหน่อยครับ เกี่ยวกับเขียน API ดึงข้อมูลมาแสดง ใน html |
|
 |
|
|
 |
 |
|
ใช้ fetch เพื่อดึงข้อมูลจาก API และใช้ Promise เพื่อจัดการกับข้อมูล
Code (PHP)
<!DOCTYPE html>
<html lang="th">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>COVID-19 Data</title>
<style>
table {
border-collapse: collapse;
width: 100%;
margin-top: 20px;
}
th, td {
border: 1px solid #dddddd;
text-align: left;
padding: 8px;
}
th {
background-color: #f2f2f2;
}
</style>
</head>
<body>
<h1>ข้อมูลผู้ป่วย COVID-19</h1>
<table id="covid-table">
<thead>
<tr id="table-headers">
<!-- หัวข้อตาราง -->
</tr>
</thead>
<tbody>
<!-- ข้อมูลจาก API -->
</tbody>
</table>
<script>
// ดึงข้อมูลจาก API
fetch("https://covid19.ddc.moph.go.th/api/Cases/round-4-line-lists")
.then(response => {
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
return response.json(); // แปลงข้อมูลเป็น JSON
})
.then(data => {
console.log(data); // ตรวจสอบข้อมูลที่ได้รับ
const tableHeaders = document.getElementById("table-headers");
const tableBody = document.getElementById("covid-table").getElementsByTagName("tbody")[0];
const patientsData = data.data; // เข้าถึงข้อมูลที่อยู่ใน `data`
// ตรวจสอบว่ามีข้อมูลจาก API หรือไม่
if (patientsData && patientsData.length > 0) {
// ดึงคีย์จากรายการแรกเพื่อสร้างหัวตาราง
const keys = Object.keys(patientsData[0]);
keys.forEach(key => {
const headerCell = document.createElement("th");
headerCell.innerText = key; // ตั้งชื่อหัวตาราง
tableHeaders.appendChild(headerCell); // เพิ่มหัวตารางลงใน thead
});
// แสดงข้อมูลแต่ละรายการ
patientsData.forEach(item => {
const row = tableBody.insertRow();
keys.forEach(key => {
const cell = row.insertCell();
cell.innerText = item[key] || "ไม่ระบุ"; // แสดงค่าหรือข้อความว่า "ไม่ระบุ"
});
});
} else {
console.warn("No data found from API.");
}
})
.catch(error => console.error("Fetch error:", error));
</script>
</body>
</html>
|
 |
 |
 |
 |
Date :
2024-11-02 14:50:13 |
By :
Manussawin |
|
 |
 |
 |
 |
|
|
 |
 |
|
 |
 |
|
|
|

|
Load balance : Server 05
|