티스토리 뷰

728x90

AJAX와 관련해서 검색하다 보면 자주 볼 수 있는 기술 4가지 입니다.

 

1. 완전 옛날 방식 XMLHttpRequest (ECMAScript 3 / 1999년)

2. 최근 방식 FetchAPI (ECMAScript 6 / 2015년)

3. jquery api (third-party / 2006년)

4. axios (third-party / 2014년)

 

브라우저에 내장된 기본 기능1번과 2번 이고

3번과 4번은 별도의 라이브러리를 사용하는 불편함이 있습니다.

 

어떤 방식이든지 결과만 잘 나오면 되겠지만

1번과 3번은 사용하지 않는 것을 권장합니다.

 

1번은 너무 오래되었고 코드가 너무 길어지는 문제가 있으며

3번 jquery는 요즘은 사용하지 않는 기술입니다.

ECMAScript 6 부터 문법이 잘 정리되고 있고

브라우저가 계속 발전하면서 jquery는 사용하지 않습니다.

 

각 기술마다 작성해야 하는 기본적인 코드 형태입니다.

 

데이터로 사용할 웹페이지의 모습입니다.

 

 

1. XMLHttpRequest

<body>
  <div id="result"></div>
  <script>
    const xhr = new XMLHttpRequest();
    xhr.onreadystatechange = callback;
    const url = 'https://jsonplaceholder.typicode.com/posts';
    xhr.open('get', url);
    xhr.send(null);
    function callback() {
      if (xhr.readyState == 4) {
        if (xhr.status == 200) {
          let result = xhr.response;
          document.querySelector('#result').innerHTML = result;
        }
      }
    }
  </script>
</body>
  • XMLHttpRequest 객체 생성
  • open 함수로 통신
  • callback 함수에서 통신 결과에 따라 응답 데이터 처리

 

 

2. FetchAPI

<body>
  <div id="result"></div>
  <script>
    const url = 'https://jsonplaceholder.typicode.com/posts';
    const ajax = fetch(url);
    ajax.then(function(response) {
      return response.text();
    }).then(function(result) {  
      document.querySelector('#result').innerHTML = result;
    });
  </script>
</body>
  • fetch 함수 실행
  • 응답결과로 받은 Response 객체에서 내용 추출 후 반환
  • 반환 데이터 처리

 

 

3. jQuery

<body>
  <div id="result"></div>  
  <script src='http://code.jquery.com/jquery-3.7.0.min.js'></script>
  <script>
    const url = 'https://jsonplaceholder.typicode.com/posts';
    $.ajax({
      url: url,
      type: 'get',
      success: function (result) {
        document.querySelector('#result').innerHTML = result;
      }
    });
  </script>
</body>
  • jquery 라이브러리 가져오기
  • ajax 함수 실행
  • success 의 콜백 함수에서 응답 데이터 처리

 

 

4. Axios

<body>
  <div id="result"></div>
  <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
  <script>
    const url = 'https://jsonplaceholder.typicode.com/posts';
    const data = axios({
      url: url,
      method: 'get'
    });
    data.then(function (result) {
      document.querySelector('#result').innerHTML = result;
    });
  </script>
</body>
  • axios 라이브러리 가져오기
  • axios 함수 실행
  • 응답 데이터 처리

 

너무 다양해서 하나를 선택하기가 애매하다면

2번 Fetch API를 선택하면 됩니다.

 

Fetch API의 사용법을 조금 더 설명하자면

1. get 요청

2. post 요청

3. post + json 요청

이렇게 3가지 정도로 다시 나누어 볼 수 있습니다.

 

get 요청 예)

<body>
  <div id="result"></div>
  <script>
    const url = 'https://jsonplaceholder.typicode.com/posts';
    const ajax = fetch(url);
    ajax.then(function(response) {
      console.log(response)
      return response.text();
    }).then(function(result) {  
      document.querySelector('#result').innerHTML = result;
    });
  </script>
</body>
  • fetch 함수에 요청할 주소만 입력
  • 파라미터는 ? 기호로 지정
    • ex) https://jsonplaceholder.typicode.com/posts?title=ABC&body=DEF

 

post 요청 예)

<body>
  <div id="result"></div>
  <script>
    const url = 'https://jsonplaceholder.typicode.com/posts';
    const formData = new FormData();
    formData.append('title', 'Title Test');
    formData.append('body', 'Body Test');
    formData.append('userId', 999);
    const ajax = fetch(url, {
      method: 'post',
      body: formData
    });
    ajax.then(function(response) {
      return response.text();
    }).then(function(result) {  
      console.log(result)
      document.querySelector('#result').innerHTML = result;
    });
  </script>
</body>
  • FormData 객체를 생성한 후 name과 value 추가
  • fetch 함수에 요청할 주소와 method / body 를 키로 가지는 객체를 함께 지정

 

post + json 요청 예)

<body>
  <div id="result"></div>
  <script>
    const url = 'https://jsonplaceholder.typicode.com/posts';
    const ajax = fetch(url, {
      method: 'post',
      body: JSON.stringify({
        'title': 'Title Test',
        'body': 'Body Test',
        'userId': 999
      }),
      headers: {
        'Content-type': 'application/json; charset=UTF-8',
      },
    });
    ajax.then(function(response) {
      return response.text();
    }).then(function(result) {  
      console.log(result)
      document.querySelector('#result').innerHTML = result;
    });
  </script>
</body>
  • body의 값으로 객체, headers의 값으로 application/json 입력
  • fetch 함수에 요청할 주소와 method / body 를 키로 가지는 객체를 함께 지정