개발노트/jQuery

[jQuery] Ajax 데이터 처리 패턴 정리

dev-mylee 2025. 1. 5. 11:22

오늘은 Ajax로 데이터 처리하면서 배운 내용들을 정리해본다.

단순히 데이터를 주고받는 게 전부가 아니라는 걸 알게 됐다.

 

1. 기본적인 Ajax 호출

가장 기본적인 형태의 Ajax 호출:

$.ajax({
    contentType: 'application/json; charset=utf-8',
    type: 'post',
    dataType: 'json',
    url: '/api/endpoint',
    data: JSON.stringify(requestData),
    success: function(response) {
        // 성공 처리
    },
    error: function(xhr, status, error) {
        // 에러 처리
    }
});

 

 

 

2. 데이터 가공해서 보내기

서버에 보낼 데이터를 가공하는 과정이 은근 중요하다:

function prepareRequestData() {
    var checkedItems = [];
    
    // 체크된 항목들 데이터 수집
    $('input:checkbox:checked').each(function() {
        var row = $(this).closest('tr');
        checkedItems.push({
            id: row.data('id'),
            status: row.data('status'),
            // 기타 필요한 데이터...
        });
    });
    
    // 최종 요청 데이터 구성
    return {
        items: checkedItems,
        userId: getCurrentUserId(),
        timestamp: new Date().toISOString()
    };
}

 

 

 

3. 응답 처리 패턴

서버 응답을 처리할 때는 단계별로 체크하는게 좋다:

function handleResponse(response) {
    // 1. 기본적인 성공/실패 체크
    if(response.msgCd !== 'M01') {
        handleError(response.msgCd);
        return;
    }
    
    // 2. 데이터 유효성 검증
    if(!response.data || !Array.isArray(response.data)) {
        alert('올바르지 않은 데이터입니다.');
        return;
    }
    
    // 3. 실제 데이터 처리
    processData(response.data);
    
    // 4. UI 업데이트
    updateUI();
    
    // 5. 사용자 피드백
    showSuccessMessage('처리가 완료되었습니다.');
}

function handleError(msgCd) {
    switch(msgCd) {
        case 'M03':
            alert('데이터가 변경되었습니다. 새로고침 후 다시 시도해주세요.');
            break;
        case 'M04':
            alert('이미 처리된 데이터입니다.');
            break;
        default:
            alert('처리 중 오류가 발생했습니다.');
    }
}

 

 

✅ 메모

1. 중복 호출 방지하기

var isProcessing = false;

function submitData() {
    if(isProcessing) {
        alert('처리 중입니다. 잠시만 기다려주세요.');
        return;
    }
    
    isProcessing = true;
    
    $.ajax({
        // ... ajax 설정
    }).always(function() {
        isProcessing = false;
    });
}

 

2. timeout 설정 잊지 말기

$.ajax({
    timeout: 30000, // 30초
    // ... 다른 설정들
});

 

3. 로딩 인디케이터 처리

function showLoading() {
    $('#loadingSpinner').show();
    $('button[type="submit"]').prop('disabled', true);
}

function hideLoading() {
    $('#loadingSpinner').hide();
    $('button[type="submit"]').prop('disabled', false);
}

 

4. CSRF 토큰 처리

$.ajax({
    // ... 다른 설정들
    beforeSend: function(xhr) {
        xhr.setRequestHeader("X-CSRF-TOKEN", 
            $("input[name='_csrf']").val());
    }
});