Sky Archive

JavaScript/JQuery

[jQuery] Ajax의 Success와 Done의 차이

Anchovy ʕ-᷅ᴥ-᷄ʔ 2022. 3. 8. 14:09

안녕하세요.🐱‍🐉

이번 글은 Ajax 대해 정리해보려고 해요.

Ajax를 사용하면서 Success와 Done의 차이에 대해 뭘까 하는 궁금증이 생겼는데 혹시 여러분은 차이가 뭔지 아시나요?


Ajax(Asynchronous JavaScript and XML)란?

  • 자바스크립트를 이용한 비동기식으로 XML 이용하여 서버와 통신하는 방식
  • 최근에는 XML보다 JSON을 더 많이 사용
  • 주로 화면 전체를 전환시키지 않고 부분적으로 처리할 때 사용
  • 페이지 일부분에만 새로운 콘텐츠를 로드하는 기능은 사용자의 전체적인 사용 경험을 향상
  • SPA(Sinlge Page Application, 브라우저에서 실행되지만 마치 소프트웨어 애플리케이션 같은 느낌을 주는 웹 기반 도구)가 등장하는 계기

2021.12.27 - SSR(Server Side Rendering)과 CSR(Client Side Rendering)

 

SSR(Server Side Rendering)과 CSR(Client Side Rendering)

SSR(Server Side Rendering) 서버 측에서 렌더링 마친 상태로 데이터가 결합된 화면을 클라이언트에 전달하는 방식 - 새로운 페이지로 이동할 때마다 요청하기 때문에 깜박거리는 현상 존재 - SPA(Single

string.tistory.com

 

Ajax의 동작 방식

브라우저에서 Ajax 요청을 담당하는 XMLHttpRequest라는 객체를 통해 서버에 정보를 요청, 응답받는다.

 

콜백 동작 순서

성공 시 : success > complete > done > always

실패 시 : error > complete > fail > always

 

jQuery를 이용한 Ajax

Ajax의 기본 Method를 이용하면 XMLHttpRequest를 직접 사용하게 되는데 때문에 이러한 복잡한 과정 없이 jQuery를 이용하면 간단하게 서버와 데이터를 주고받을 수 있습니다. 또한 크로스 브라우징 문제도 jQuery가 알아서 해결해주고 여러 가지 편리한 기능들을 제공한다.

 

$.ajax([settings]) 함수의 property

https://api.jquery.com/jquery.ajax/

$.ajax ({
  url	: "url", // (Required) 요청이 전송될 URL 주소
  type	: "GET", // (default: ‘GET’) http 요청 방식
  async : true,  // (default: true, asynchronous) 요청 시 동기화 여부
  cache : true,  // (default: true, false for dataType 'script' and 'jsonp') 캐시 여부
  timeout : 3000, // (ms) 요청 제한 시간 안에 완료되지 않으면 요청을 취소하거나 error 콜백 호출
  data  : {key : value}, // 요청 시 전달할 데이터
  processData : true, // (default: true) 데이터를 컨텐트 타입에 맞게 변환 여부
  contentType : "application/json", // (default: 'application/x-www-form-urlencoded; charset=UTF-8')
  dataType    : "json", // (default: Intelligent Guess (xml, json, script, or html)) 응답 데이터 형식
  beforeSend  : function () {
    // XHR Header 포함, HTTP Request 하기전에 호출
  },
  success : function(data, status, xhr) {
    // 정상적으로 응답 받았을 경우 파라미터는 응답 바디, 응답 코드 그리고 XHR 헤더
  },
  error	: function(xhr, status, error) {
    // 응답을 받지 못하거나 정상적인 응답이지만 데이터 형식을 확인할 수 없는 경우
  },
  complete : function(xhr, status) {
    // success와 error 콜백이 호출된 후에 반드시 호출, try - catch - finally의 finally 구문과 동일
  }
});

 

success와 .done()의 차이

success / error의 형태

$.ajax({
  url: 'URL',
  type: 'POST',
  data: yourData,
  datatype: 'json',
  success: function (data, textStatus, xhr) { },
  error: function (xhr, textStatus, errorThrown) { },
  complete: function(xhr, status) { }
});

 

.done() / .fail()의 형태

$.ajax({
  url: 'URL',
  type: 'POST',
  data: yourData,
  datatype: 'json'
})
.done(function(data, textStatus, xhr) { });
.fail(function(xhr, textStatus, errorThrown) { });
.always(function(data|xhr, textStatus, xhr|errorThrown) { });
.then(function(data, textStatus, xhr|errorThrown) { });

형태를 보면 거의 유사하다는 것을 알 수 있는데 success는 jQuery에서 성공 콜백의 기본 이름으로, ajax 호출 옵션으로 정의된다. 그러나 $.Deferreds와 더 정교한 콜백의 구현 이후, done은 어떤 deferred에서도 호출될 수 있기 때문에 성공 콜백을 구현하는 데 선호되는 방법이다. 또한 promises 패턴인 .done()이 좀 더 깔끔하다.

 

done의 장점

done의 좋은 점은 $.ajax의 반환 값이 이제 애플리케이션의 다른 곳과 연결될 수 있는 지연된 promise이라는 것.

그래서 ajax를 몇 군데 다른 곳에서 걸려고 한다면 이 ajax 호출을 만드는 함수의 옵션으로 성공 함수를 전달하는 대신, 함수 자체에서 $.ajax를 반환하고 콜백을 done, fail, then 등으로 바인딩할 수 있다. always은 요청의 성공 여부에 관계없이 실행되고 done는 성공할 때만 트리거 된다.

ex.

function xhr_get(url) {
  return $.ajax({
    url: url,
    type: 'get',
    dataType: 'json',
    beforeSend: showLoadingImgFn
  })
  .always(function() {
    // remove loading image maybe
  })
  .fail(function() {
    // handle request failures
  });
}

xhr_get('/index').done(function(data) {
  // do stuff with index data
});

xhr_get('/id').done(function(data) {
  // do stuff with id data
});

유지관리 용이성 측면에서 중요한 이점은 애플리케이션별 기능에 ajax 메커니즘을 적용했다는 것이다. 나중에 앱의 다른 모든 참조는 동일하게 유지하면서 다르게 동작하게 해야 한다면 xhr_get의 정의만 변경하면 된다. ($.ajax 호출이 필요하거나, 다른 ajax 메서드를 사용하거나, jQuery를 삭제하거나..)

 

$.Deferred로 할 수 있는 또 다른 것은 $.ajax 요청이 성공하더라도 서버의 오류를 pipe를 사용하여 트리거할 수 있다.

ex.

function xhr_get(url) {
  return $.ajax({
    url: url,
    type: 'get',
    dataType: 'json'
  })
  .pipe(function(data) {
    return data.responseCode != 200 ?
      $.Deferred().reject( data ) :
      data;
  })
  .fail(function(data) {
    if ( data.responseCode )
      console.log( data.responseCode );
  });
}

xhr_get('/index').done(function(data) {
  // will not run if json returned from ajax has responseCode other than 200
});

- jQuery 1.8부터 pipe는 더 이상 then과 같은 방식으로 사용되지 않음.

 

 

※ $.Deferred에 대해  -> http://api.jquery.com/category/deferred-object/

Promise에 대해 -> https://tangoo91.tistory.com/42

 

 

 

 

 

 

 

 

 

 

ref.

jQuery api docs

https://api.jquery.com/jquery.ajax/

https://stackoverflow.com/questions/8840257/jquery-ajax-handling-continue-responses-success-vs-done