Sử dụng fetch() lấy dữ liệu JSON từ API (JSONPlaceholder) rồi render thành bảng HTML.
Ví dụ
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <style> body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; } .sample { font-size: 18px; font-weight: 500; color: red; } </style> </head> <body> <h1>Tạo HTML từ JSON data</h1> <div class="sample">TÊN NHÂN VIÊN</div> <table border="1" class="employee"></table> <button class="Btn">NHẤN VÀO ĐÂY</button> <h3> Nhấn nút để điền bảng nhân viên </h3> <script> let sampleEle = document.querySelector(".employee"); document.querySelector(".Btn").addEventListener("click", () => { fetch("https://jsonplaceholder.typicode.com/users") .then((response) => response.json()) .then((result) => { result.forEach((element) => { sampleEle.innerHTML += "<tr><td>" + element.name + "</td></tr>"; }); }); }); </script> </body> </html>
Kết quả
Bảng hiển thị danh sách tên nhân viên từ API giả.