코딩과 결혼합니다

Fetch 연습하기 (2주차 숙제) 본문

2세/기타

Fetch 연습하기 (2주차 숙제)

코딩러버 2023. 5. 8. 13:54
728x90

웹개발 종합반 2주차 - Fetch 연습하기 (2주차 숙제)

 

 

 

 

아래와 같이 현재 서울의 날씨를 실시간으로 보여주면 된다.

 

 

선행

 

    <div class="mytitle">
        <h1>내 생애 최고의 영화들</h1>
        <div>현재 서울의 날씨 : <span id="temp">20</span></div>
        <button onclick="hey()">영화 기록하기</button>
    </div>

제목과 버튼 사이에 추가로 html 작성

        $(document).ready(function () {
            fetch("http://spartacodingclub.shop/sparta_api/weather/seoul").then(res => res.json()).then(data => {
                console.log(data)
            })
        })

미리 만들어둔 fetch 기본골격을 <script>안에 넣기

 

 

 

 

 

 

직접해보기

 

 

        $(document).ready(function () {
            fetch("http://spartacodingclub.shop/sparta_api/weather/seoul").then(res => res.json()).then(data => {

               let temp = data['temp']
               let temp_html = `<div>현재 서울의 날씨 : ${temp}도</div>`
               $('#temp').append(temp_html)
            })
        })

*script

    <div class="mytitle">
        <h1>내 생애 최고의 영화들</h1>
        <div>현재 서울의 날씨 : <span id="temp">20</span></div>
        <button onclick="hey()">영화 기록하기</button>
    </div>

*html

*서울 실시간 날씨 url

 

 

 

1. 변수 이름을 temp로 하고 서울 날씨 url에서 데이터 'temp' 값을 가져온다.

     let temp = data['temp']

2. 변수 temp_html의 백틱(``)안에 어떤 형식으로 어떤 데이터 값을 보여줄건지 

    let temp_html = `<div>현재 서울의 날씨 : ${temp}도</div>`

3. 그리고 그 데이터를 어느 위치에 붙일것인지 입력

    $('#temp').append(temp_html)

 

 

 

 

실시간 온도가 잘 보여진다. 이제 원래의 데이터를 없애야겠다. 근데 생각처럼 안 없어짐..😂

 

 

 

 

해결

 

        $(document).ready(function () {
            fetch("http://spartacodingclub.shop/sparta_api/weather/seoul").then(res => res.json()).then(data => {
               let number = data['temp']
               $('#temp').text(number)
            })
        })

데이터가 하나 밖에 없는데 쓸데없는 코드를 적었나 보다 ㅋㅋㅋ

더 단순하게 만들 수 있다. 그냥 html의

<span id="temp">20</span>

 #temp의 값을

   (temp의 데이터 값을 담고 있는)변수 number의 값으로 바꾸어 보여주면 됨!

 

참고로 보기 헷갈려서 변수이름을 temp에서 number로 변경

 

 

 

 

 

분명 5월 6일날 글자 바꾸기로 마술을 부려보겠다고 나댔었는데 응용도 못하다니

정신차리자 이채원🤦‍♀️