본문 바로가기
Javascript/GMA(2302~)

230428 자바스크립트 async( ) / fetch( ) 활용하여 Json 파일 출력하기

by hyerin1201 2023. 5. 18.


HTML

<body>
  <h1>회원정보</h1>
  <div id="result"></div>
</body>

CSS

* {
  margin: 0;
  padding: 0;
}

table {
  width: 300px;
  margin: 10px;
  display: inline-block;
  border-collapse: collapse;
}
tr {
  border: 1px solid #ccc;
  border-collapse: collapse;
}
th {
  border: 1px solid #ccc;
  width: 80px;
}
td {
  width: 210px;
  padding: 5px;
}

Javascript

async function init() {
  const resoponse = await fetch('https://jsonplaceholder.typicode.com/users/');
  const users = await resoponse.json();
  display(users)
}

//테이블태그로 출력될수 있도록 함수
function display(users) {
  const result = document.querySelector("#result");
  let string = "";
  users.forEach((user) => {
    string += `
      <table>
        <tr><th>이름</th><td>${user.name}</td></tr>
        <tr><th>아이디</th><td>${user.username}</td></tr>
        <tr><th>이메일</th><td>${user.email}</td></tr>
      </table>
    `
  });
  result.innerHTML = string;
}
init();