🍭Ajax 기본 통신 구조
🎈type, url, data, dataType을 지정하여 호출을 하며 success타입에 따라 데이터를 리턴 받을 수 있다.
$.ajax({
type: "POST",
url: url,
data: data,
success: success,
dataType: dataType
});
🎈type : http 타입 ( get, post)
🎈url : 호출하는 URL 정보
🎈async : true(기본), 비동기 처리, false(동기처리)
🎈data : URL호출시 보내는 파라미터 (key,value / json)
🎈dataType : http통신 이후 응답되는 데이터 타입
🎈success : function(res) : ajax통신 이후 실행 함수
$.post( "ajax/test.html", function( data ) {
$( ".result" ).html( data );
});
🎈post 형식으로 지정할땐 $.post get방식은 $.get형식으로 호출한다.
var jqxhr = $.post( "example.php", function() {
alert( "success" );
})
.done(function() {
alert( "second success" );
})
.fail(function() {
alert( "error" );
})
.always(function() {
alert( "finished" );
});
// Perform other work here ...
// Set another completion function for the request above
jqxhr.always(function() {
alert( "second finished" );
});
🎈success() jQuery 3.0부터 제거되었습니다.
🎈대신 이 콜백 함수를 사용할수 있습니다. error() / complete() / done() / fail() / always()
$.post( "test.php", { name: "John", time: "2pm" } );
$.post( "test.php", { 'choices[]': [ "Jon", "Susan" ] } );
$.post( "test.php", $( "#testform" ).serialize() );
위와 같이 ajax 구문에 대해 기본적으로 알아보았다. 이렇게 비동기를 사용함에 따라 문제가 발생하는 부분이 있다.
바로 AJAX 비동기 통신에 대한 실행 순서에 대한 제어가 필요하였고 기존 사용시 무한 콜백함수로 인하여 콜백지옥(Callback Hell)을 발생하였다.
// setTimeout함수 실행 후 3초 뒤 호출되는 함수를 CallBack함수라고한다.
setTimeout(function() {
console.log('CallBackHell');
}, 3000);
이러한 코드구조로 인한 가독성 하락과 유지보수어려움에 따라 Promise와 async를 통해 실행 순서를 제어할수 있다.
비동기 처리 시점이 명확하며 연속된 비동기 처리가 가능하고 작업상태 확인이 쉽고 코드의 유지보수가 쉽다.
function getData(callback) {
// new Promise() 프로미스를 사용하기 위해서 비동기 호출을 아래와 같이 감싸 호출한다.
return new Promise(function(resolve, reject) {
$.get('url 주소/products/1', function(response) {
// 데이터를 받으면 resolve() 호출
if(response) {
// 성공시 resolve를 통한 값전달 -> .then을 통해 성공값 전달
resolve(response);
} else {
// 실패시 reject() 실행 -> .then이 아닌 catch를 통해 에러내역 확인 및 로직실행
reject();
}
});
});
}
// 비동기 실행이 끝나고 호출되는 then()
getData().then(function(successResult) {
// resolve()의 결과 값이 여기로 전달됨
console.log(successResult); // $.get()의 reponse 값이 tableData에 전달됨
}).catch(function(err) {
$.post(contextPath + "/sessionClose", function(result) {});
});
🍭Promise 3가지 상태
🎈Promise 처리과정 시 new Promise()로 프로미스를 생성하고 종료될 때까지 3가지 상태를 갖습니다.
🎉. Pending(대기) : 비동기 처리 미진행, 이행과 거절도 안된 초기 상태를 뜻함
🎉. Fulfilled(이행) : 비동기 처리 완료, 결과값을 반환한 상태
🎉. Rejected(실패) : 비동기
🎈Pending(대기)
new Promise()로 Promise 생성과 종료사이에 3가지 상태값(Pending, Fulfilled, Rejected)을 갖습니다.
new Promise() 메서드를 호출시 콜백 함수를 선언할 수 있고, 콜백 함수인자값은 resolve, reject를 갖습니다.
new Promise(function(resolve, reject) {
// 비동기 통신 로직을 호출
$.get('url 주소', function(response) {
});
});
🎈Fulfilled(이행)
resolve 콜백함수 실행 상태를 이행(Fulfilled)상태라고 한다. 통상 실행이 완료된 상태, 비동기 통신이 완료된 상태를 뜻한다. then()함수를 사용하여 성공값을 전달 받을 수 있다.
new Promise(function(resolve, reject) {
// 비동기 통신 로직을 호출
$.get('url 주소', function(response) {
resolve(response);
});
});
function getData(callback) {
// new Promise() 프로미스를 사용하기 위해서 비동기 호출을 아래와 같이 감싸 호출한다.
return new Promise(function(resolve, reject) {
$.get('url 주소/products/1', function(response) {
// 데이터를 받으면 resolve() 호출
if(response) {
// 성공시 resolve를 통한 값전달 -> .then을 통해 성공값 전달
resolve(response);
} else {
// 실패시 reject() 실행 -> .then이 아닌 catch를 통해 에러내역 확인 및 로직실행
reject();
}
});
});
}
// 비동기 실행이 끝나고 호출되는 then()
getData().then(function(successResult) {
// resolve()의 결과 값이 여기로 전달됨
console.log(successResult); // $.get()의 reponse 값이 tableData에 전달됨
}).catch(function(err) {
$.post(contextPath + "/sessionClose", function(result) {});
});
🎈Rejected(실패)
비동기 통신이 실패가 되었을때 콜백함수 reject를 호출 시 catch를 통해 에러를 처리 한다.
function getData(callback) {
// new Promise() 프로미스를 사용하기 위해서 비동기 호출을 아래와 같이 감싸 호출한다.
return new Promise(function(resolve, reject) {
$.get('url 주소/products/1', function(response) {
// 데이터를 받으면 resolve() 호출
if(response) {
// 성공시 resolve를 통한 값전달 -> .then을 통해 성공값 전달
resolve(response);
} else {
// 실패시 reject() 실행 -> .then이 아닌 catch를 통해 에러내역 확인 및 로직실행
reject();
}
});
});
}
// 비동기 실행이 끝나고 호출되는 then()
getData().then(function(successResult) {
// resolve()의 결과 값이 여기로 전달됨
console.log(successResult); // $.get()의 reponse 값이 tableData에 전달됨
}).catch(function(err) {
$.post(contextPath + "/sessionClose", function(result) {});
});
댓글