코딩/웹개발

Fetch 기초

americanoallday 2025. 1. 22. 15:15

fetch란

인터넷을 통해 데이터를 요청하고 받아오는 과정

 

fetch 기본 구문

fetch("여기에 URL을 입력").then(res => res.json()).then(data => {
		console.log(data)
})

 

사용 예시 1)

<!doctype html>
<html lang="ko">

<head>
    <meta charset="UTF-8">
    <title>Fetch 시작하기</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script>
        function hey() {
            let url = 'http://spartacodingclub.shop/sparta_api/seoulair';
            fetch(url).then(res => res.json()).then(data => {
                let rows = data['RealtimeCityAir']['row'];
                rows.forEach(row => {
                    let gu_name = row['MSRSTE_NM'];
                    let gu_mise = row['IDEX_NM'];
                    console.log(gu_name, gu_mise);
                });
            })
        }
    </script>
</head>

<body>
    <button onclick="hey()">fetch 연습!</button>
</body>

</html>

 

예제 2) 업데이트 누를 경우 구 정보와 미세먼지 농도 정보 리스트가 출력되며, 40이상인 경우 빨간색으로 표시

 

주요 코드 : 

    <script>
        function q1() {
            let url = 'http://spartacodingclub.shop/sparta_api/seoulair';
            $('#names-q1').empty();

            fetch(url).then(res => res.json()).then(data => {
                let rows = data['RealtimeCityAir']['row'];
                rows.forEach(row => {
                    let gu_name = row['MSRSTE_NM'];
                    let gu_mise = row['IDEX_MVL'];

                    let temp_html=``;
                    if(gu_mise>40){
                        temp_html = `<li class="bad">${gu_name}:${gu_mise}</li>`;
                    }else{
                        temp_html = `<li>${gu_name}:${gu_mise}</li>`;
                    }
                    
                    $('#names-q1').append(temp_html);
                });
            })
        }
    </script>

 

전체 코드

<!doctype html>
<html lang="ko">

<head>
    <meta charset="UTF-8">
    <title>미세먼지 API로Fetch 연습하고 가기!</title>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

    <style type="text/css">
        div.question-box {
            margin: 10px 0 20px 0;
        }
        .bad{
            color: red;
        }
    </style>

    <script>
        function q1() {
            let url = 'http://spartacodingclub.shop/sparta_api/seoulair';
            $('#names-q1').empty();

            fetch(url).then(res => res.json()).then(data => {
                let rows = data['RealtimeCityAir']['row'];
                rows.forEach(row => {
                    let gu_name = row['MSRSTE_NM'];
                    let gu_mise = row['IDEX_MVL'];

                    let temp_html=``;
                    if(gu_mise>40){
                        temp_html = `<li class="bad">${gu_name}:${gu_mise}</li>`;
                    }else{
                        temp_html = `<li>${gu_name}:${gu_mise}</li>`;
                    }
                    
                    $('#names-q1').append(temp_html);
                });
            })
        }
    </script>

</head>

<body>
    <h1>Fetch 연습하자!</h1>

    <hr/>

    <div class="question-box">
        <h2>1. 서울시 OpenAPI(실시간 미세먼지 상태)를 이용하기</h2>
        <p>모든 구의 미세먼지를 표기해주세요</p>
        <p>업데이트 버튼을 누를 때마다 지웠다 새로 씌여져야 합니다.</p>
        <button onclick="q1()">업데이트</button>
        <ul id="names-q1">
        </ul>
    </div>
</body>

</html>

 

 

$(document).ready(function() { ... })jQuery에서 사용되는 함수로,

**“HTML 문서가 완전히 로드되고 DOM(Document Object Model)이 준비되면 실행하라”**는 의미.

 

웹 페이지의 내용이 다 불러와진 후에 실행할 코드를 작성하는 방법

브라우저가 HTML을 로드하는 동안, 스크립트가 너무 빨리 실행되면 HTML 요소를 찾지 못할 수 있음

$(document).ready()는 이런 문제를 방지하고, 페이지가 준비된 후 코드를 실행하도록 보장해줍니다.

 

예시)

$(document).ready(function () {
            let url = "http://spartacodingclub.shop/sparta_api/seoulair";
            fetch(url).then(res => res.json()).then(data => {
               let mise = data['RealtimeCityAir']['row'][0]['IDEX_NM'];
               $('#msg').text(mise);
            })
        })
  • fetch 함수를 사용하여 주어진 URL에서 데이터를 가져오기
  • .then(res => res.json()) 반환 된 응답(response)내용을 JSON 형식으로 만들기
  • .then(data => { ... }) JSON 데이터를 가져온 후
  • temperature 값을 변수에 담는다!
  • 선택자 선택 후 IDEX_NM의 값을 문자열로 삽입


특정 텍스트에 값 적용 원할 경우 <span> 지정

<span>은 HTML에서 사용되는 인라인(줄 안의) 요소로, 특정 텍스트나 부분적인 내용을 묶어서 스타일을 적용하거나 조작할 때 사용

 

1. 특정 텍스트에 스타일 적용

2. 특정 텍스트에 자바스크립트 기능 추가

<p>이 문장에서 <span id="clickMe">여기를 클릭</span>하면 실행됩니다.</p>

<script>
  document.getElementById('clickMe').addEventListener('click', function() {
    alert('클릭했어요!');
  });
</script>

3. CSS 클래스를 통해 스타일 재사용

<style>
  .highlight {
    color: blue;
    font-weight: bold;
  }
</style>

<p>이 문장에서 <span class="highlight">강조된 부분</span>이 있습니다.</p>

 


 

'코딩 > 웹개발' 카테고리의 다른 글

배포해보기 + 파이썬 맛보기  (0) 2025.01.23
Firebase 시작하기  (0) 2025.01.22
JQuery 기초  (0) 2025.01.21
HTML 기초 2 + Javascript 기초  (0) 2025.01.20
HTML 기초 1  (0) 2025.01.17