본문 바로가기
Frontend/javascript

[JavaScript] 자바스크립트 동기/비동기 서버 데이터 가져오기 - Ajax

by couque 2023. 4. 17.
반응형

자바스크립트에서 현재 페이지에서 페이지 이동없이 데이터를 불러오는 방법으로 ajax를 사용하는데,

ajax를 사용하여 데이터를 가져오는 방법 중에 동기와 비동기로 데이터를 가져오는 방법에 대해 알아보자.


# Async : 비동기로 서버 데이터 가져오기

    1. ajax 함수 선언

var AjaxComm = ({
    ajaxAsync : function(url, data, success, fail){

        $.ajax({
            dataType : "json",
            type : "POST",
            data : data,
            success : function(data){
                if(success){
                    success(data);
                }
            },
            error : function(xhr, status, error){
                //alert("code : " + xhr.status + "\n message : " + xhr.responseText + "\n error : " + error);
                if(fail){
                    fail(error);
                }else{
                    alert(error);
                }
            }
        });

    }
});

    2. ajax 함수 호출하기

AjaxComm.ajaxAsync('${targetUrl}', '${data}',
    function(result){
    	alert('success');
    },
    function(result){
    	alert('fail');
    }
);

 

# Sync : 동기로 서버 데이터 가져오기

    1. ajax 함수 선언

var AjaxComm = ({
    ajaxAsync : function(url, data, success, fail){

        $.ajax({
            async : false,
            dataType : "json",
            type : "POST",
            data : data,
            success : function(data){
                if(success){
                    success(data);
                }
            },
            error : function(xhr, status, error){
                //alert("code : " + xhr.status + "\n message : " + xhr.responseText + "\n error : " + error);
                if(fail){
                    fail(error);
                }else{
                    alert(error);
                }
            }
        });

    }
});

    2. ajax 함수 호출하기

AjaxComm.ajaxSync('${targetUrl}', '${data}',
    function(result){
    	alert('success');
    },
    function(result){
    	alert('fail');
    }
);

 

반응형

댓글