JAVASCRIPT

자바스크립트 문제 풀기 (JSON,fetch) 명언json에서 랜덤으로 배경화면과 명언 랜덤 출력하기

김도현2 2023. 4. 15. 18:40
반응형

자바스크립트 문제 풀기 (JSON,fetch) 명언json에서 랜덤으로 배경화면과 명언 랜덤 출력하기

json 에서 데이터와 배경사진을 랜덤으로 불러와 출력해보겠습니다.

 

 

 

 

 

 

 

 

1번 문제

JSON 데이터를 가져온 후 콘솔창에 결과를 표시해 보세요.

가져온 데이터가 어떤 구조로 이루어져 있는지 살펴보는 것이 목표입니다.

 

fetch("json/dummy01.json")
    .then((res)=> res.json())
    .then((obj) => {
        console.log(obj);
    });

 

json 데이터를 콘솔창에 띄운 모습입니다.

 

 

 

 

2번 문제

JSON데이터에서 명언 1개를 가져와 내용과 말한 사람을 표시해 보세요.

무작위 수를 사용해 명언을 가져온 후 명언과 말한 사람을 나눠서 화면에 표시합니다.

 

<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    
    <title>Document</title>
    
    <style>
        @import url('https://webfontworld.github.io/Montserrat/Montserrat.css');
        * {
            padding: 0;
            margin: 0;
        }
        .wrap {
            width: 1000px;
            height: 700px;
            background-color: #101010;
            text-align: center;
            color: #fff;
            font-family: "Montserrat";
            background-size: cover;
            background-position: center;
            background-repeat: no-repeat;
            background-image: url("https://source.unsplash.com/random/?cat");
            z-index: 1;
            
        }
        .button {
            display: inline;
            padding: 5px;
            background-color: #2f00ff;
            border-radius: 10px;
            color:#fff;
            cursor: pointer;
        }
        .say {
            width: 800px;
            height: 30%;
            text-align: center;
            align-items: center;
            font-size: 30px;
            padding: 170px 120px;
            z-index: 10;
            
            background: radial-gradient(rgba(0,0,0,0.5)40%, rgba(0,0,0,0), transparent );
        }
        .say span {
            width: 800px;
            height: 300px;
            padding: 50px;
        }
        .name {
            font-weight: bold;
            z-index: 10;
            line-height: 4.2;
            height: 70px;
            background: radial-gradient(rgba(0,0,0,0.8)20%, rgba(0,0,0,0) );
        }
    </style>
</head>
<body>
    <div class="wrap">
        <div class="button">
            <span>click</span>
        </div>
        <div class="say">
            <span></span>
        </div>
        <div class="name">
            <span></span>
        </div>
    </div>
</body>

<script>

    //선택자
    const wrap = document.querySelector(".wrap");
    const say = document.querySelector(".say span");
    const name = document.querySelector(".name span");
    const button = document.querySelector(".button");
    let random = Math.round(Math.random()*30);  //랜덤숫자 0~30

    fetch("json/dummy01.json")
        .then((res)=> res.json())   //json파일 읽어오기
        .then((obj) => {            //읽어온 데이터를 json으로 변환
            data = obj.quotes;      //json에 있는 quotes만 받아오기
            
            say.innerText = data[random].quote;             //처음 보여주기용 명언
            name.innerText = "- " + data[random].author;    //처음 보여주기용 이름
            
            button.addEventListener("click",()=>{           //button 함수부여
                location.reload();                          //리프레쉬

                random = Math.round(Math.random()*30);      //버튼 누를때마다 숫자 재부여
                
                say.innerText = data[random].quote;         //새로운 숫자달고 명언
                name.innerText = "- " + data[random].author;//새로운 숫자달고 이름

            })
        });
   
</script>
</html>

 

HTML 에서 "say", "name", "button" 클래스를 가진 요소들을 JavaScript에서 선택합니다~ 

random 변수에 0부터 30까지의 랜덤한 정수를 저장합니다!

 

fetch() 함수를 사용해서 "dummy01.json" 파일을 읽어옵니다.

.then() 메소드를 사용해서 응답(Response) 데이터를 JSON 변환합니다.

 

변환된 JSON 객체에서는 "quotes" 배열에 명언 데이터가 저장되어 있습니다. 이것을 data 변수에 저장합니다.

 

button 요소에 클릭 이벤트를 추가합니다. 버튼을 클릭할 때마다 random 변수에 새로운 0부터 30까지의 랜덤한 정수를 할당을 하여 data[random]을 사용해서 새로운 명언과 작성자를 선택하고, say와 name 요소들에 각각 업데이트합니다.

 

이렇게 하면, 버튼을 누를 때마다 새로운 랜덤한 명언과 작성자가 표시되는 간단한 명언 웹 페이지가 만들어집니다~!

 

 

.wrap 클래스에 https://source.unsplash.com/random/?cat 랜덤으로 배경화면을 뽑아주는 링크를 넣습니다.

 

그 후 location.reload() 리프레쉬 메서드를 넣어 배경화면이 버튼을 누를때마다 메서드를 실행해

배경화면이 바뀌게끔 만들었습니다.