< Java Script > 비동기 통신 이용한 실습
이번에는 비동기 통신을 응용하는 실습을 포스팅하겠습니다.
들어가기 앞서
해당 html과 Json 링크는 강의 자료로 저작권 문제가 있을 까봐 공유는 안하겠습니다.
그냥 이런 식으로 응용되는구나 정도만 알아주시면 충분할 거 같습니다.
우선 json 부터 알아보겠습니다.
이미지 부분을 계층 이라고 합니다.
계층 별로 필요한 데이터를 뽑아와 사용 할 수 있도록 계층을 나눕니다.
Json 객체에 대해 필수로 알아야 할 항목 3개 꼭 기억하자!!
- key 는 문자열로 value 는 어떤 것이던 올 수 있지만 문자열인 경우엔 반드시 "" 로 감싸야 한다.
- parse() : JSON 문자열을 파람으로 받아서, 스크립트 객체로 변환하는 함수.
- stringify() : 파라미터를 받아서, JSON 객체로 변환하는 함수.
<작업방법>
JSON 을 요청한다고 Request 해야한다.
이때 사용되는 대표적 API 가 fetch() 이다.
이 객체는 내부적으로 XHR 과 같은 역할을 하고,
요즘 가장많이 쓰이는 비동기 서버 통신 API 이다.
fetch 에는 요청할 URL 정보를 넘겨주면 되고,
내부적으로는 PRomise 로 정의 도어있기 때문에 성공/실패를 정의할 수도 있다.
하지만 서버에 요청 시 실패가 뜨는 경우엔 사용될 데이터가 없기 때문에 대부분은 그냥 성공 위주로 코딩한다.
* Request 객체 : 스크립트에서 특정 서버에 요청을 담당하는 객체
나중에 fetch 에서 이 객체의 정보를 연동, 실제 요청 및 결과를 리턴 받도록 한다.
가장먼저
request , fetch 를 이용해서 JSON 요청을 하는 함수를 정의한다.
이때 반드시 비동기 통신을 해야기 때문에 async 를 이용해서 요청한다.
async function pending(){
const reqUrl = "https://mdn.github.io/learning-area/javascript/oojs/json/superheroes.json";
//Request 객체를 이용, 요청 준비 작업
const request = new Request(reqUrl);
// 연결 준비가 되었으니, 요청 및 데이터를 받도록 합니다.
const response = await fetch(request);
const superHeroes = await response.json();
console.log(superHeroes);
}
pending();
우선 이렇게 html 에 스크립트 태그에 이렇게 코드 작성 후 실행하면
이렇게 JSON 이 잘 출력되는 걸 볼 수 있다.
영웅들의 공통 정보는 Header 에 정의하고 각 개별 정보는 카드 형식으로 정의하자.
따라서 showHeader(), showHero() 를 정의 후, 받아낸 JSON 을 파람으로 넘긴다.
async function pending(){
const reqUrl = "https://mdn.github.io/learning-area/javascript/oojs/json/superheroes.json";
//Request 객체를 이용, 요청 준비 작업
const request = new Request(reqUrl);
// 연결 준비가 되었으니, 요청 및 데이터를 받도록 합니다.
const response = await fetch(request);
const superHeroes = await response.json();
console.log(superHeroes);
showHeader(superHeroes); // 여기에 정의할 예정인 메서드를 미리 작성하자
showHero(superHeroes);
}
pending();
showHeader() 정의하기
function showHeader(obj){
//1. header ele 를 찾아서 객체화 한다.
const header = document.querySelector("header");
//h1 크기로 영웅의 타이틀을 넣을 예정, 따라서 h1 ele 를 생성 후 header 하위에 추가한다.
const myH1 = document.createElement("h1");
myH1.textContent = obj.squadName;
header.appendChild(myH1);
// p ele 생성해서 myh1 하위에 배치하자
const myP = document.createElement("p");
myP.textContent = `HomeTown:${obj.homeTown} // 조직일자: ${obj.formed}`;
header.appendChild(myP);
}
하고 refresh(F5) 해보자
showHero() 정의
function showHero(obj){
//Section 영역에 각 영웅의 정보를 rendering 시킨다.
const section = document.querySelector('section');
//영웅들을 parsing 해서 가져온다.
const heroes = obj.members;
console.log(heroes);
}
이렇게 작성 후 콘솔에 파싱이 잘 되었나 확인하자.
확인결과
function showHero(obj){
//Section 영역에 각 영웅의 정보를 rendering 시킨다.
const section = document.querySelector('section');
//영웅들을 parsing 해서 가져온다.
const heroes = obj.members;
console.log(heroes);
for (const hero of heroes) {
// hero 는 배열 내의 각 영웅 객체이다.
// 위 코드에서 자동으로 리턴해주니, 해당 정보를 추출해서 랜더링만 하면 끝난다.
//section 에 article 이라는 시멘틱 요소 생성
console.log(hero.powers)
const myArticle = document.createElement("article");
// 영웅들의 이름은 h2로
const myH2 = document.createElement("h2");
// 일반 정보는 p 태그
const param1 = document.createElement("p");
const param2 = document.createElement("p");
const param3 = document.createElement("p");
// 영웅의 고유 능력치는 list 형태로 (ul)
const myList = document.createElement("ul");
myH2.textContent = hero.name;
param1.textContent = `코드네임 : ${hero.secretIdentity}`;
param2.textContent = `Age : ${hero.age}`;
param3.textContent = `SuperPowers : `;
JSON 에 superPowers 는 배열로 담겨져 있으니 다시 배열로 빼내야한다
const superPowers = hero.powers;
for (const power of superPowers) {
// 각 능력은 ul 하위의 list로출력
const listItem = document.createElement("li");
console.log(power);
listItem.textContent = power;
myList.appendChild(listItem);
}
이렇게 하고 이제 위에 article 을 createElement 한 myAriticle을 저장한다
//article node 에 모두 추가
myArticle.appendChild(myH2);
myArticle.appendChild(param1);
myArticle.appendChild(param2);
myArticle.appendChild(param3);
myArticle.appendChild(myList);
//section 노드에 모두 추가
section.appendChild(myArticle);
실행 해보면
이렇게 뜨면 성공이다!
[전체코드]
async function pending(){
const reqUrl = "https://mdn.github.io/learning-area/javascript/oojs/json/superheroes.json";
//Request 객체를 이용, 요청 준비 작업
const request = new Request(reqUrl);
// 연결 준비가 되었으니, 요청 및 데이터를 받도록 합니다.
const response = await fetch(request);
const superHeroes = await response.json();
console.log(superHeroes);
// 영웅들의 공통 정보는 Header 에 정의하고 각 개별 정보는 카드 형식으로 정의하자.
// 따라서 showHeader(), showHero() 를 정의 후, 받아낸 JSON 을 파람으로 넘긴다.
showHeader(superHeroes);
showHero(superHeroes);
}
function showHeader(obj){
//1. header ele 를 찾아서 객체화 한다.
const header = document.querySelector("header");
//h1 크기로 영웅의 타이틀을 넣을 예정, 따라서 h1 ele 를 생성 후 header 하위에 추가한다.
const myH1 = document.createElement("h1");
myH1.textContent = obj.squadName;
header.appendChild(myH1);
// p ele 생성해서 myh1 하위에 배치하자
const myP = document.createElement("p");
myP.textContent = `HomeTown:${obj.homeTown} // 조직일자: ${obj.formed}`;
header.appendChild(myP);
}
function showHero(obj){
//Section 영역에 각 영웅의 정보를 rendering 시킨다.
const section = document.querySelector('section');
//영웅들을 parsing 해서 가져온다.
const heroes = obj.members;
console.log(heroes);
for (const hero of heroes) {
// hero 는 배열 내의 각 영웅 객체이다.
// 위 코드에서 자동으로 리턴해주니, 해당 정보를 추출해서 랜더링만 하면 끝난다.
//section 에 article 이라는 시멘틱 요소 생성
console.log(hero.powers)
const myArticle = document.createElement("article");
// 영웅들의 이름은 h2로
const myH2 = document.createElement("h2");
// 일반 정보는 p 태그
const param1 = document.createElement("p");
const param2 = document.createElement("p");
const param3 = document.createElement("p");
// 영웅의 고유 능력치는 list 형태로 (ul)
const myList = document.createElement("ul");
myH2.textContent = hero.name;
param1.textContent = `코드네임 : ${hero.secretIdentity}`;
param2.textContent = `Age : ${hero.age}`;
param3.textContent = `SuperPowers : `;
// superPower 은 배열에 담겨있으니 다시 꺼내옴
const superPowers = hero.powers;
for (const power of superPowers) {
// 각 능력은 ul 하위의 list로출력
const listItem = document.createElement("li");
console.log(power);
listItem.textContent = power;
myList.appendChild(listItem);
}
//article node 에 모두 추가
myArticle.appendChild(myH2);
myArticle.appendChild(param1);
myArticle.appendChild(param2);
myArticle.appendChild(param3);
myArticle.appendChild(myList);
//section 노드에 모두 추가
section.appendChild(myArticle);
}
}
pending();