10.07. 미니캠프_웹개발종합반(2-8~3-2)

5w31892p·2022년 10월 7일
0

미니캠프

목록 보기
4/17

Ajax

  • jQuery 임포트한 페이지에서만 동작
  • Ajax 기본 골격 (외우는 것이 아니라 복사해서 붙혀쓰는 것)
  • type: "GET" > GET 방식으로 요청
  • url > 요청할 url
  • data > 요청하면서 함께 줄 데이터 (post에서만 사용, get에서는 비워둠)
$.ajax({
  type: "GET",
  url: "http://openapi.seoul.go.kr:8088/6d4d776b466c656533356a4b4b5872/json/RealtimeCityAir/1/99",
  data: {}, 
  success: function(response){ // 서버에서 준 결과를 response라는 변수에 담음
    console.log(response) // 서버에서 준 결과를 이용해서 나머지 코드를 작성
  }
})
  • .empty() : 요소 자체가 아니라 요소의 내용을 지움
    • .append() 사용 전 ajax 시작 전에 붙힌다.
  1. 서울시 미세먼지 API
<script>
        function q1() {
            $('#names-q1').empty()
            $.ajax({
                type: "GET",
                url: "http://openapi.seoul.go.kr:8088/6d4d776b466c656533356a4b4b5872/json/RealtimeCityAir/1/99",
                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']

                        let temp_html = ``
                        if (gu_mise > 35) {
                            temp_html = `<li class="bad">${gu_name} : ${gu_mise}`
                        } else {
                            temp_html = `<li>${gu_name} : ${gu_mise}`
                            }
                        $('#names-q1').append(temp_html)
                    }
                }
            })
        }
</script>
  1. 서울시 따릉이 API
<script>
        function q1() {
            $('#names-q1').empty()
            $.ajax({
                type: "GET",
                url: "http://spartacodingclub.shop/sparta_api/seoulbike",
                data: {},
                success: function (response) {
                    let rows = response['getStationList']['row']
                    for (let i = 0; i < rows.length; i++) {
                        let name = rows[i]['stationName']
                        let cnt = rows[i]['rackTotCnt']
                        let bike = rows[i]['parkingBikeTotCnt']

                        let temp_html = ``
                        if (bike < 5) {
                            temp_html = `<tr class="little">
                                            <td>${name}</td>
                                            <td>${cnt}</td>
                                            <td>${bike}</td>
                                         </tr>`
                        } else {
                            temp_html = `<tr>
                                            <td>${name}</td>
                                            <td>${cnt}</td>
                                            <td>${bike}</td>
                                         </tr>`
                        }
                        $('#names-q1').append(temp_html)
                    }
                }
            })
        }
</script>

1,2번 모두 if문으로 ~보다 클 경우, ~보다 작을 경우를 정해서
한쪽엔 class를 두고 css로 색상을 다르게 한 후 적용

  1. 고양이 API
<script>
  function q1() {
    $.ajax({
      type: "GET",
      url: "https://api.thecatapi.com/v1/images/search",
      data: {},
      success: function (response) {
        let imgurl = response[0]['url']
        $('#img-cat').attr('src', imgurl)
      }
    })
  }
</script>
  • jQuery로 이미지를 가져오는 방법은
    • $('#id').attr('src', let으로 선언한 이미지url이름)

  • 로딩이 되자마자 호출
$(document).ready(function(){
	alert('다 로딩됐다!')
    >q1() 등 이렇게 바로 함수 불러오게도 가능
});
  1. 환율 숙제
  • 맨 처음 $(document).ready 를 통해 로딩 되자마자 호출
  • 달러 값 하나만 그때 그때 바뀌기 때문에 반복문 X
<script>
    $(document).ready(function () {
        q1()
    });
    function q1() {
       $.ajax({
 	       type: "GET",
           url: "http://spartacodingclub.shop/sparta_api/rate",
           data: {},
           success: function (response) {
	           let rates = response['rate']
               let temp_html = `<span>${rates}</span>`
               $('#names-q1').append(temp_html);
           }
        })
    }
</script>

3강에서는 Python, 크롤링, mongoDB

0개의 댓글