본문 바로가기
SQL 개발일지

[웹개발 종합반 2주차] 서버와 통신하기 Ajax

by 노랑사랑팽이 2022. 10. 21.

🔖06. 서버 클라이언트 통신 이해하기

🔎 서울시 미세먼지 OpenAPI

딕션너리안에 리스트가 있는 형태

http://openapi.seoul.go.kr:8088/6d4d776b466c656533356a4b4b5872/json/RealtimeCityAir/1/99

 

🔎 Jsonview

https://chrome.google.com/webstore/detail/jsonview/chklaanhfefbnpoihckbnefhakgolnmc?hl=ko 

 

JSONVue

Validate and view JSON documents

chrome.google.com

 

🔎 API

은행창구 같은 것.

같은 예금 창구에서도 개인 고객이냐 기업 고객이냐에 따라 가져와야 하는 것, 처리해주는 것이 다른 것처럼 클라이언트가 요청할 때도 '타입'이 존재

 

🔎GET

테이터 조회(Read) 요청

ex) 영화 목록 조회

서버주소? 데이터 정보 & 데이터 정보

    
https://movie.naver.com/movie/bi/mi/basic.nhn?code=161967
* 서버 주소: https://movie.naver.com/movie/bi/mi/basic.nhn
* 영화 정보: code=161967

google.com/search?q=아이폰&sourceid=chrome&ie=UTF-8
 * q=아이폰               (검색어)
 * sourceid=chrome        (브라우저 정보)
* ie=UTF-8                (인코딩 정보)
  • ? : 전달할 데이터가 작성된다는 의미
  • & : 전달할 데이터가 더 있다는 의미

즉, ?앞에 서버에 데이터를 요청해 가져올 예정이다.

 

🔎POST

데이터 생성(Create), 변경(Update), 삭제(Delete) 요청

ex) 회원가입, 회원탈퇴, 비밀번호 수정


🔖07. Ajax 시작하기

🔎Ajax 기본 골격

$.ajax({
    type: "GET",
    url: "여기에URL을입력",
    data: {},
    success: function(response){
    	console.log(response)
    }
})

 

🔎서울시 미세먼지 OpenAPI 데이터 불러오기

<head>
    <script>
        $.ajax({
          type: "GET",
          url: "http://spartacodingclub.shop/sparta_api/seoulair",
          data: {},
          success: function (response) {
            console.log(response)
		  }
	</script>
</head>

 

🔎서울시 미세먼지 OpenAPI 데이터  구, 미세먼지 값 추출

<head>
    <script>
        $.ajax({
          type: "GET",
          url: "http://spartacodingclub.shop/sparta_api/seoulair",
          data: {},
          success: function (response) {
            let rows = response['RealtimeCityAir']['row']
            for (let i = 0; i < rows.length; i++) {
              let gu_name = rows[i]['MSRSTE_NM']
              let gu_mise = rows[i]['IDEX_MVL']
              console.log(gu_name, gu_mise)
            }
          }
        })
	</script>
</head>


🔖08. Ajax 연습하기

🔎업데이트 버튼 누를때마다 구, 미세먼지 값 html에 붙이기

  <script>
        function q1() {
// 여기에 코드를 입력하세요
          $('#names-q1').empty()
          $.ajax({
            type: "GET",
            url: "http://spartacodingclub.shop/sparta_api/seoulair",
            data: {},
            success: function (response) {
              console.log(response)

              let rows = response['RealtimeCityAir']['row']
              for(let i = 0; i < rows.length; i++){
                let gu_name = rows[i]['MSRSTE_NM']
                let gu_mise = rows[i]['IDEX_MVL']

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

              }
            }
          })
        }
    </script>

 

🔎미세먼지 값이 일정수준 이상이면 CSS로 빨간색나오도록 설정

    <style>
        .bad {
          color: red;
        }
    </style>
    
    
    <script>
    function q1() {
// 여기에 코드를 입력하세요
      $('#names-q1').empty()
      $.ajax({
        type: "GET",
        url: "http://spartacodingclub.shop/sparta_api/seoulair",
        data: {},
        success: function (response) {
          console.log(response)

          let rows = response['RealtimeCityAir']['row']
          for(let i = 0; i < rows.length; i++){
            let gu_name = rows[i]['MSRSTE_NM']
            let gu_mise = rows[i]['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>


☀️ 느낀점

퀴즈가 아니지만, 멈춰두고 한번 구현해봤다.

    <script>
        function q1() {
// 여기에 코드를 입력하세요
          $('#names-q1').empty()
          $.ajax({
            type: "GET",
            url: "http://spartacodingclub.shop/sparta_api/seoulair",
            data: {},
            success: function (response) {
              console.log(response)

              let rows = response['RealtimeCityAir']['row']
              for(let i = 0; i < rows.length; i++){
                let gu_name = rows[i]['MSRSTE_NM']
                let gu_mise = rows[i]['IDEX_MVL']

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

나는 if문안에서 바로바로 html붙이기를 했는데,

영상으로 보고 빈 temp_html을 비워두고 조건문 들어올때마다 temp_html을 넣어주고 조건문나와 반복문에서 html붙여주기를 하니 같은 코드를 2번 반복해 쓰지 않아도 되서 가독성 있고 좋다는 생각이 들었다.

어제 백준 알고리즘 문제를 풀다가 arr를 한번 지정해주고 빈 박스처럼 반복해서 쓰는 코드를 봤는데, 이런식으로 코드를 많이 짜는구나! 싶었다.

같은 동작을 하는 코드를 여러번 반복해서 쓰는 것은 비효율적인 코드인 것 같다. 좀 더 생각하는 힘을 길러야겠다.

댓글