본문 바로가기

TIL

[웹개발 종합반] 2주차 fetch

fetch 함수 이용해서 미세먼지 데이터 불러오기 

 

1. 요소 추가하기

 

1-1. J-Query

 

      function q1() {
        fetch("http://spartacodingclub.shop/sparta_api/seoulair")
          .then((res) => res.json())
          .then((data) => {
            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);
            });
          });
      }

 

 

1-2. JavaScript

      function q1() {
        fetch("http://spartacodingclub.shop/sparta_api/seoulair")
          .then((res) => res.json())
          .then((data) => {
            let rows = data["RealtimeCityAir"]["row"];
            rows.forEach((a) => {
              let gu_name = a["MSRSTE_NM"];
              let gu_mise = a["IDEX_MVL"];

              const first = document.createElement("li");
              first.textContent = `${gu_name} : ${gu_mise}`;
              namesq1.append(first);
            });
          });
      }

 

자바스크립트만을 사용해도 똑같은 결과가 나타나며, id값을 변경하여 적용함. (아직 id 에 - 값이 있을 때 접근하는 방법을 모르겠음 ..)

 


 

2. 조건문 사용하여 미세먼지값이 40이 넘는 요소는 빨간색으로 지정

 

2-1. J-Query

 

     function q1() {
        fetch("http://spartacodingclub.shop/sparta_api/seoulair")
          .then((res) => res.json())
          .then((data) => {
            let rows = data["RealtimeCityAir"]["row"];
            rows.forEach((a) => {
              let gu_name = a["MSRSTE_NM"];
              let gu_mise = a["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);
            });
          });
      }

 

2-2. JavaScript

 

      function q1() {
        fetch("http://spartacodingclub.shop/sparta_api/seoulair")
          .then((res) => res.json())
          .then((data) => {
            let rows = data["RealtimeCityAir"]["row"];
            rows.forEach((a) => {
              let gu_name = a["MSRSTE_NM"];
              let gu_mise = a["IDEX_MVL"];

              const first = document.createElement("li");

              if (gu_mise > 40) {
                first.textContent = `${gu_name} : ${gu_mise}`;
                first.classList.add("bad");
              } else {
                first.textContent = `${gu_name} : ${gu_mise}`;
              }

              namesq1.append(first);
            });
          });
      }

'TIL' 카테고리의 다른 글

TIL 23.05.17  (0) 2023.05.18
[웹개발종합반] 3주차 DB SQL/ NoSQL  (0) 2023.04.18
[웹개발종합반] 3주차 python/ 크롤링  (0) 2023.04.18
[웹개발종합반] 2주차 J-Query 연습하기  (0) 2023.04.15
사전캠프 계획 ~ 5.15  (1) 2023.04.13