개발일지

개발일지 (feat 스파르타코딩 웹개발 2주차)

JDI HAN 2022. 9. 18. 12:30

Ajax는 자바스크립트를 통해 서버와 브라우저가 웹페이지를 리로드하지 않고(비동기 방식) 페이지 일부만을 위해 데이터를 가져오는 기법

 

Ajax는 jQuery를 임포트한 페이지에서만 동작 가능합니다.

 

Ajax 기본 골격

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

 

사용예시

<script>
    function q1() {
      $(`#names-q1`).empty()
      $.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']

            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>
  • 이미지 바꾸기 : $("#아이디값").attr("src", 이미지URL);
  • 텍스트 바꾸기 : $("#아이디값").text("바꾸고 싶은 텍스트");

 

로딩후 호출

$(document).ready(function ()
{
   $.ajax({
     type: "GET",
     url: "http://spartacodingclub.shop/sparta_api/weather/seoul",
     data: {},
     success: function (response) {
       // console.log(response)
       let msg = response['temp']
       $('#temp').text(msg)
     }
   })
});