Lina's Toolbox

[스파르타 내일배움캠프_AI 웹개발 과정] 2일차 복습/ fetch 본문

스파르타 내일 배움 캠프 AI 웹개발 과정/front-end

[스파르타 내일배움캠프_AI 웹개발 과정] 2일차 복습/ fetch

Woolina 2024. 6. 25. 22:28

자바스크립트

Fetch

우리가 웹브라우저에 주소를 치고 들어가듯이, url을 부르는 코드

제이쿼리를 연동해야 사용할 수 있음.

 

기본 골격

fetch("여기에 URL을 입력") // 이 URL로 웹 통신을 요청한다. 괄호 안에 다른 것이 없다면 GET!
	.then(res => res.json()) // 통신 요청을 받은 데이터는 res라는 이름으로 JSON화 한다
	.then(data => { 
		console.log(data) // 개발자 도구에 찍어보기
}) // JSON 형태로 바뀐 데이터를 data라는 이름으로 붙여 사용한다

fetch("") : 괄호 안에 url만 입력한 다면 기본상태인 GET 요청.

.then : 응답이 오면 받은 데이터를 여기 저장할게. (res로 보통 쓰지만 res말고 다른 이름을 지정해도됨. 그 아래 data도 같음)

=> :  저장 후 그 데이터를 이 코드에 이용

 

예제: 미세먼지 데이터 처리하기

이렇게 생긴 JSON 파일을 열 경우,

//JSON 파일도 그냥 복잡한 형태의 딕셔너리

 

fetch("http://spartacodingclub.shop/sparta_api/seoulair") // 기본 요청(GET)
	.then(res => res.json()) // 요청해서 받은 데이터를 JSON화
	.then(data => { // JSON화 한 데이터를 다시 data로 이름짓기
		let rows = data['RealtimeCityAir']['row']
		rows.forEach((a) => {
			// 미세먼지 데이터 리스트의 길이만큼 반복해서 하나씩 개발자 도구에서 보기
			// 구의 이름, 미세먼지 수치 값을 개발자 도구에서 찍어보기
			console.log(a['MSRSTE_NM'], a['IDEX_MVL'])
		})
	})

 

 

예제 2

버튼을 누를 때마다 지역별 미세먼지 정보 받아서 화면에 뿌려주는 코드

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

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

		<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
    <style type="text/css">
        div.question-box {
            margin: 10px 0 20px 0;
        }
    </style>

    <script>
        function q1() {
            fetch("http://spartacodingclub.shop/sparta_api/seoulair").then((response) => response.json()).then((data) => {
                    $('#names-q1').empty()
										let rows = data['RealtimeCityAir']['row']
                    rows.forEach((a) => {
                        let gu_name = a['MSRSTE_NM']
												let gu_mise = a['IDEX_MVL']
                        let 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">
            <li>중구 : 82</li>
            <li>종로구 : 87</li>
            <li>용산구 : 84</li>
            <li>은평구 : 82</li>
        </ul>
    </div>
</body>

</html>

 

예제 3

이런 데이터의 경우, 작가와 명언 정보만 받아서 화면에 뿌려주기

<!DOCTYPE html>
<html lang="en">

<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>
  <script src="https://code.jquery.com/jquery-3.7.0.min.js" integrity="sha256-2Pmvv0kuTBOenSvLm6bvfBSSHrUJ+3A7x6P5Ebd07/g=" crossorigin="anonymous"></script>
</head>
<!-- 여백으로 레이아웃 만들기 -->
<style>
  body {
    background-image: url("https://s3.ap-northeast-2.amazonaws.com/materials.spartacodingclub.kr/webjong/images/background.jpg");
    background-position: center;
    background-size: cover;
    color: white;
  }

  .navbar {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .weather {
    display: flex;
    align-items: center;
    margin-right: 30px;
  }

  .container {
    display: flex;
    flex-direction: column;
    /* Flex 안의 아이템들을 세로 방향으로 배치합니다. */
    justify-content: center;
    /* 주축 방향으로 가운데 정렬합니다. */
    align-items: center;
    /* 교차축 방향으로 가운데 정렬합니다. */
    height: 100vh;
    text-align: center;
  }

  .footer {
    position: fixed;
    left: 0;
    bottom: 0;
    width: 100%;
    text-align: center;
    font-weight: bold;
    padding: 20px 0;
  }

  .greeting {
    margin-bottom: 50px;
  }

  .motto {
    margin-bottom: 100px;
  }

  .logo {
    height: 32px;
    margin-left: 30px;
  }
</style>

<body>
  <nav class="navbar">
    <img class="logo" src="https://s3.ap-northeast-2.amazonaws.com/materials.spartacodingclub.kr/webjong/images/sparta-logo.svg" alt="" srcset="" />
    <div class="weather">
      <img src="">
      <span>20ºC</span>
    </div>

  </nav>

  <div class="container">
    <div class="greeting">
      <h1>Hello, My name!</h1>
      <h1 id="current-time"></h1>
    </div>

    <div class="motto">
      <h3>My life's motto</h3>
      <h2>웃으면 행복해집니다.</h2>
    </div>
  </div>
  <div class="footer">
    <p id="quoteAuthor">- 작자 미상 -</p>
    <p id="quoteContent">멋진 명언입니다. 아이스크림을 먹으면 행복해져요.</p>
  </div>

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

    // 시간 chatgpt
    function displayCurrentTime() {
      var currentTime = new Date();
      var hours = currentTime.getHours();
      var minutes = currentTime.getMinutes();
      var seconds = currentTime.getSeconds();

      // Add leading zeros to minutes and seconds if they are less than 10
      minutes = (minutes < 10 ? "0" : "") + minutes;
      seconds = (seconds < 10 ? "0" : "") + seconds;

      // Determine if it's AM or PM
      var meridiem = hours >= 12 ? "PM" : "AM";

      // Convert to 12-hour format
      hours = hours % 12;
      hours = hours ? hours : 12;

      // Display the time in HH:MM:SS format
      var timeString = hours + ":" + minutes + ":" + seconds + " " + meridiem;

      // Display the time in an element with id "current-time"
      document.getElementById("current-time").innerHTML = timeString;
    }

    // Call the displayCurrentTime function every second to update the time
    setInterval(displayCurrentTime, 1000);

    // 명언
    let url = "https://api.quotable.io/random";
    fetch(url)
    .then(res => res.json())
    .then(data => {
        console.log(data);
        let author = data['author']
        let content = data['content']

        let authorMsg = `- ${author} -`
        let contentMsg = `" ${content} "`

        $("#quoteAuthor").text(authorMsg);
        $("#quoteContent").text(contentMsg);
    })

  </script>
</body>

</html>

 

 

저기서 이미지를 불러오고 싶을 경우

<nav class="navbar">
  <img class="logo" src="https://s3.ap-northeast-2.amazonaws.com/materials.spartacodingclub.kr/webjong/images/sparta-logo.svg" alt="" srcset="" />
	<div class="weather">
	    <img id="weather-icon" src="https://ssl.gstatic.com/onebox/weather/64/partly_cloudy.png">
	    <p id="weather-msg">날씨 맑음, 20ºC</p>
	</div>
</nav>

// 날씨
let weather_url = "http://spartacodingclub.shop/sparta_api/weather/seoul";
fetch(weather_url)
    .then(res => res.json())
    .then(data => {
        // console.log(data);
        let temp = data['temp']
        let icon_url = data['icon']
        let message = `${temp}ºC`
        $('#weather-msg').text(message)
        $('weather-icon').attr("src", icon_url)
    })

 

 

&('#이미지태그').attr("src", "이미지 주소") 메서드로 이미지 동적으로 설정 가능

 


컴파일러와 인터프리터의 차이

  • 컴파일러: 통으로 한번에 실행함
  • 인터프리터: 바로바로 통역함. (1줄씩 코드 실행) ex. 파이썬