웹 개발에서 서버로부터 받은 JSON 데이터를 활용해 HTML을 동적으로 생성하는 작업은 매우 흔합니다. 이 글에서는 자바스크립트의 fetch() 메서드를 사용해 JSONPlaceholder API에서 사용자 목록을 가져온 뒤, 그 결과를 HTML 테이블에 렌더링하는 방법을 예제와 함께 살펴봅니다.
참고: JSONPlaceholder는 테스트 및 프로토타이핑 용도로 제공되는 가상의 무료 온라인 REST API입니다.
예제 코드
<!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>JSON arrays</h1>
<div class="sample">EMPLOYEE NAME</div>
<table border="1" class="employee"></table>
<button class="Btn">CLICK HERE</button>
<h3>
Click on the above button to fill the employee table
</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 += "<td>" + element.name;
});
});
});
</script>
</body>
</html>
코드 설명
document.querySelector(".employee")로 데이터를 삽입할 테이블 요소를 선택합니다.- 버튼을 클릭하면
fetch("https://jsonplaceholder.typicode.com/users")가 실행되어 사용자 데이터를 비동기적으로 요청합니다. response.json()을 통해 응답 본문을 JSON 객체로 변환합니다.forEach()로 각 사용자 객체를 순회하며name값을 테이블 셀(<td>)에 하나씩 추가합니다.
실행 결과
페이지를 처음 열면 다음과 같은 초기 화면이 표시됩니다.

'CLICK HERE' 버튼을 클릭하면 API에서 가져온 직원 이름들이 테이블에 순서대로 채워집니다.
