AJAX(Asynchronous JavaScript And XML)에 대해

oversleep·2025년 2월 3일
post-thumbnail

AJAX는:

웹 페이지의 일부분만을 업데이트하기 위한 비동기 통신 기술.
전통적인 웹 페이지는 새로운 데이터가 필요할 때마다 전체 페이지를 다시 로드해야 함.
AJAX를 사용하면 페이지 전체를 새로고침하지 않고도 서버와 데이터를 주고받을 수 있음.

실제 사용 예시:

// 기본적인 AJAX 요청 예시
const xhr = new XMLHttpRequest();
xhr.open('GET', 'https://api.example.com/data', true);

xhr.onload = function() {
    if (xhr.status === 200) {
        const data = JSON.parse(xhr.responseText);
        console.log('데이터 수신 성공:', data);
    }
};

xhr.send();

더 간단한 방식인 Fetch API:

fetch('https://api.example.com/data')
    .then(response => response.json())
    .then(data => console.log('데이터 수신 성공:', data))
    .catch(error => console.error('에러 발생:', error));

AJAX의 주요 장점들:

  1. 사용자 경험 향상: 페이지 전체를 새로고침하지 않아도 되므로 더 부드러운 사용자 경험 제공
  2. 서버 부하 감소: 필요한 데이터만 요청하므로 서버 자원을 효율적으로 사용
  3. 실시간성: 실시간 데이터 업데이트가 가능 (예: 채팅, 실시간 검색)

실제 활용 사례:

  • 검색창의 자동완성 기능
  • 소셜 미디어의 "좋아요" 버튼
  • 장바구니에 상품 추가
  • 실시간 댓글 시스템

최신 웹 개발에서는 AJAX를 직접 사용하기보다는 axios나 fetch API와 같은 현대적인 도구들을 더 많이 사용함.

  1. 에러 처리 방법:
fetch('https://api.example.com/data')
    .then(response => {
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        return response.json();
    })
    .then(data => {
        console.log('성공:', data);
    })
    .catch(error => {
        console.error('에러 발생:', error);
        // 사용자에게 에러 메시지 표시
        alert('데이터를 불러오는데 실패했습니다.');
    });
  1. POST 요청 보내기:
fetch('https://api.example.com/submit', {
    method: 'POST',
    headers: {
        'Content-Type': 'application/json',
    },
    body: JSON.stringify({
        username: '홍길동',
        age: 25
    })
})
.then(response => response.json())
.then(data => console.log('성공:', data));
  1. axios 라이브러리 사용 예시:
// GET 요청
axios.get('https://api.example.com/data')
    .then(response => console.log(response.data))
    .catch(error => console.error(error));

// POST 요청
axios.post('https://api.example.com/submit', {
    username: '홍길동',
    age: 25
})
.then(response => console.log(response.data));
  1. 실제 활용 예시 - 실시간 검색:
const searchInput = document.querySelector('#search');

searchInput.addEventListener('input', function(e) {
    const searchTerm = e.target.value;
    
    // 입력이 너무 짧으면 요청하지 않음
    if (searchTerm.length < 2) return;
    
    fetch(`https://api.example.com/search?q=${searchTerm}`)
        .then(response => response.json())
        .then(results => {
            // 검색 결과 표시
            displayResults(results);
        })
        .catch(error => console.error('검색 중 에러:', error));
});

function displayResults(results) {
    const resultsContainer = document.querySelector('#results');
    resultsContainer.innerHTML = ''; // 기존 결과 삭제
    
    results.forEach(result => {
        const div = document.createElement('div');
        div.textContent = result.title;
        resultsContainer.appendChild(div);
    });
}
  1. 파일 업로드:
const formData = new FormData();
const fileField = document.querySelector('input[type="file"]');

formData.append('file', fileField.files[0]);

fetch('https://api.example.com/upload', {
    method: 'POST',
    body: formData
})
.then(response => response.json())
.then(data => {
    console.log('업로드 성공:', data);
})
.catch(error => {
    console.error('업로드 실패:', error);
});

이러한 AJAX 요청들은 보통 다음과 같은 상황에서 사용:

  • 폼 제출: 페이지 새로고침 없이 데이터 전송
  • 데이터 실시간 업데이트: 주식 가격, 날씨 정보 등
  • 무한 스크롤: 사용자가 페이지 하단에 도달할 때 추가 데이터 로드
  • 자동 저장: 문서 편집기에서 주기적으로 내용 저장
profile
궁금한 것, 했던 것, 시행착오 그리고 기억하고 싶은 것들을 기록합니다.

0개의 댓글