[2] AJAX - 객체 response, 속성 status

o:kcalb·2022년 12월 30일
0

Ajax

목록 보기
2/9
post-thumbnail

fetch API에서는 CallBack 함수를 주게 되면,
CallBack 함수를 fetch API가 실행시킬 때,
함수의 첫 번째 인자의 값으로 response 객체를 준다.


1. 객체 response

  • 패치를 통해 우리가 요청을 했을 때,
    웹서버가 응답한 그 결과를 갖고 있는 객체.
  • 데이터가 response라는 것이고, 그 안의 여러 가지 속성을 작업에 활용할 수 있다.
  • 인자의 이름은 굳이 response가 아니어도 된다.

기본 예제

fetch('html').then(function(response){
	console.log(response); //객체 response를 콘솔 출력
});


2. 속성 status

객체 response 속성 중 status라는 속성은
웹브라우저와 웹서버가 통신할 때 웹서버의 응답 결과를 알려준다.

response.status 라고 입력하여 출력할 수 있다.

👍 status: 200

파일을 정상적으로 찾았으며, 응답에 성공했다.

👎 status: 404

파일을 정상적으로 찾지 못 했으며, 응답에 실패했다. (not found)


Status 활용 예제 01

fetch('javaScript').then(function(response){
  console.log(response); 
  //response 객체 정보 갖고 오기
  
  console.log(response.status); 
  // response라는 객체에서 status 정보 갖고 오기
});

Status 활용 예제 02 (if문)

if문 을 사용해 response.status 의 값에 따라
👍 200: article의 innerHTML 기입
👎 404: article의 404 텍스트를 기입

<div onclick="
fetch('JavaScript').then(function(response){
  if(response.status == '404') {
    document.querySelector('article').innerHTML = '404';
  } else {
    response.text().then(function(text){
      document.querySelector('article').innerHTML = text;
    });
  }
});
">JavaScript</div>
profile
모든 피드백 받습니다 😊

0개의 댓글

관련 채용 정보