두개의 화면을 가진 웹 앱

 

SPA = 하나의 어플리케이션이 여러개의 화면을 가지고 화면을 전환하면서 보여주는 방식 (라우팅)

 

const container = document.querySelector('#root');
const ajax = new XMLHttpRequest();
const content = document.createElement('div');
const NEWS_URL = 'https://api.hnpwa.com/v0/news/1.json'
const CONTENT_URL = 'https://api.hnpwa.com/v0/item/@id.json';

ajax.open('GET', NEWS_URL, false); // method, Url, async
ajax.send();

const newsFeed = JSON.parse(ajax.response);
const ul = document.createElement('ul');

window.addEventListener('hashchange', function(){
    const id = location.hash.substring(1);
    
    ajax.open('GET', CONTENT_URL.replace('@id', id), false);
    ajax.send();

    const newsContent = JSON.parse(ajax.response);
    const title = document.createElement('h1');

    title.innerHTML = newsContent.title;

    content.appendChild(title);    
});

for(let i=0; i<newsFeed.length; i++){
    const li = document.createElement('li');
    const a = document.createElement('a');
    
    a.href = `#${newsFeed[i].id}`;
    a.innerHTML = `${newsFeed[i].title} (${newsFeed[i].comments_count})`;
    
    li.appendChild(a);
    ul.appendChild(li);
}

container.appendChild(ul);
container.appendChild(content);

만든 해커뉴스 화면에서 해당 타이틀의 글을 클릭하면 ajax를 통해 각 해커뉴스 id에 관한 정보를 가져오는 상세 기능을 구현했다. 앵커 태그를 클릭할 때, 해시 값이 바뀌는 이벤트를 통해 해당 글의 id 값으로 라우팅 처리하는 식의 기능을 구현할 수 있다.

 

 

 

https://bit.ly/37BpXiC

 

패스트캠퍼스 [직장인 실무교육]

프로그래밍, 영상편집, UX/UI, 마케팅, 데이터 분석, 엑셀강의, The RED, 국비지원, 기업교육, 서비스 제공.

fastcampus.co.kr

 

본 포스팅은 패스트캠퍼스 환급 챌린지 참여를 위해 작성되었습니다.

 

#패스트캠퍼스 #패캠챌린지 #직장인인강 #직장인자기계발 #패스트캠퍼스후기 #김민태의프론트엔드아카데미:제1강JavaScript&TypeScriptEssential

'study' 카테고리의 다른 글

패스트캠퍼스 챌린지 9일차  (0) 2022.02.01
패스트캠퍼스 챌린지 8일차  (0) 2022.01.31
패스트캠퍼스 챌린지 6일차  (0) 2022.01.29
패스트캠퍼스 챌린지 5일차  (0) 2022.01.28
패스트캠퍼스 챌린지 4일차  (0) 2022.01.27

+ Recent posts