본문 바로가기
언어/Javascript, Typescript

AJAX란?, AJAX사용방법

by minhyeok.lee 2023. 3. 29.
반응형

AJAX란?

AJAX (Asynchronous JavaScript And XML)는 서버와 비동기적으로 데이터를 주고받는 자바스크립트 기술이다.

 

* 서버는 데이터를 요구하면 데이터를 보내주는 프로그램이다.

 유튜브, 넷플릭스 등은 고객(클라이언트)이 영상 데이터를 요구하면 서버에서 영상데이터를 보내준다.

 네이버 웹툰, 카카오 웹툰 등은 고객(클라이언트)이 웹툰(이미지) 데이터를 요구하면서버에서 웹툰데이터를 보내준다.

 

데이터를 가져오기 위해서는 개발자가 만든 API를 사용해야 한다.

원하는 데이터 URL이 뭔지 알아야하고 해당 URL로 GET요청을 해야한다.

 

따라서 GET요청을 하는 URL을 직접입력하여 요청하거나

<form action = "요청 URL" method ="get" >
 <button type = "submit">요청</button>
</form>

위 코드와 같은 버튼을 눌러 해당 요청 URL을 GET하는 방법이 있다.

 

하지만 위와 같은 방법을 사용하면 브라우저 전체가 새로고침된다는 단점이 있다.

AJAX로 GET요청을 하면 새로고침 없이 서버에게 GET 요청을 할 수 있고 새로고침이 없어서 웹페이지 전환이 부드러워진다.

 

 


 

AJAX 사용방법

1. 초기 ajax 방식

var httpRequest;

httpRequest.onreadystatechange = function(){
    // 서버의 응답에 따른 로직을 여기에 작성한다.
    if(this.readState == 4 && this.status == 200) {
    	console.log(ajax.responseText)
    }
};

httpRequest.open('GET', '요청 URL', true);
httpRequest.send();

 

 

2. 최근 ajax 방식

 2.1) Promise방식

fetch('요청 URL')
    .then((response) => {
    	if(!response.ok) throw new Error('ERROR!');
    	return response.json()
    })
    .then(결과) => {
    	console.log(결과)
    })
    .catch(() => console.log('ERROR'));

Promise방식에 대한 상세 내용

2023.03.22 - [언어/Javascript,TypeScript] - [js] Promise 정리

 

[js] Promise 정리

Promise정리 [ State, Producer, Consumer(then, catch, finally), Promise Chaining, Error Handling ] Promise란? 1. Promise는 비동기 작업에 대한 javascript 개체이다. 2. Promise는 State라는 상태값을 가지고 Promise 생상부분과 사

kfdd6630.tistory.com

 

 2.2) async...await 방식

async function getData() {
    let response = await fetch('요청 URL');
    if(!response.ok) throw new Error('ERROR!');
    let result = await response.json();
    console.log(result);
}

getData().catch(() => console.log('ERROR'));

async...await 방식에 대한 상세 내용

2023.03.22 - [언어/Javascript,TypeScript] - [js] async & await 정리

 

[js] async & await 정리

async & await 사용방법, useFul Promise APIs(Promise.all(), Promise.race()) async & await란? 1. async와 await는 자바스크립트의 비동기 처리 패턴 중 가장 최근에 나온 문법이다. 2. 비동기 방식을 사용함에 있어 Promise

kfdd6630.tistory.com

 

3. axios 사용방식 (외부 라이브러리)

axios.get('요청 URL')
  .then((result) => {
      console.log(result.data);
  }).catch(() => {
      console.log('ERROR!');
  })

 

반응형

댓글