AJAX - Response 받아서 처리하기

김민재·2021년 6월 17일
0

Gotcha JavaScript!

목록 보기
32/45

AJAX

1.HTTP 요청을 보냈을 때 발생하는 이벤트 종류에 대해서 알아보자.
2.이벤트 핸들러를 등록해 활용하는 방법에 대해서 알아보자.

  • req 객체에 대해서 readyState 속성이 변할 때마다 해당 메소드가 호출된다.
  • this.readyState출력하면 req 객체에 메소드로서 등록된 함수이되었기 때문에 함수안에서 this에 접근했을 때는 req에 접근할 수 있다.
  • this 즉, req의 readyState속성에 접근하면 req 객체에 readyState 속성을 출력할 수가 있다.
  <script>
    var req = new XMLHttpRequest();
    req.onreadystatechange = function a() {
      console.log(this.readyState, this.status);
      if (this.readyState == 4 && this.status == 200) {
        console.log(this.response);
        // 이부분의 다른 로직을 추가하면 정상적으로 수신되었을 시
      }
    }
    req.open("GET", "./data.txt");
    req.send();
  </script>

readyState 속성

AJAX 요청의 상태에 따라 값이 0~4까지 변하게 된다.

onreadystatechange 속성

readyState가 변할 때마다 호출되는 콜백 함수이다.

status 속성

HTTP response의 응답 헤더에 기록된 코드이다.

-onreadystatechange 이벤트 핸들러 안에서 readyState, status속성에 접근을 하면 데이터가 정상적으로 수신되었을 때 해당 값을 출력할 수 있다.

응답을 정상적으로 수신한 경우

readyState : 4
status : 200

기타 callback function 활용 가능한 속성

-기타 이벤트에 대해서 이벤트를 등록하고 활용할 수 있다.
-애드이벤트리스너메소드를 활용할 수 도 있다.
onloadstart
onprogress
onabort
onerror
onload
ontimeout
onloadend

profile
자기 신뢰의 힘을 믿고 실천하는 개발자가 되고자합니다.

0개의 댓글