programing

jQuery ajax와 ES6의 약속

kingscode 2023. 4. 1. 14:24
반응형

jQuery ajax와 ES6의 약속

ES6 약속을 사용하여 jQuery를 통해 포스트 요청을 하려고 합니다.

다음과 같은 기능이 있습니다.

getPostPromise(something, anotherthing) {
  return new Promise(function(resolve, reject) {
    $.ajax({
      url: someURL,
      type: 'post',
      contentType: 'application/json; charset=utf-8',
      data: JSON.stringify(
        something: something,
        anotherthing: anotherthing
      }),
      dataType: 'json',
      success: resolve,
      error: reject
    });
  });
}

이렇게 부르죠

getPostPromise(
  'someFooStuff',
  'someBarStuff'
).then(
  function(returnedData) {
    console.log("Good: ", returnedData);
  },
  function(responseObject) {
    console.log("Bad: ", responseObject);
  }
).catch(
  function(errorThrown) {
    console.log("Exception: ", errorThrown);
  }
);

서버가 예상대로 응답을 반환하고 요청 본문이 JSON 형식이지만 콘솔 출력은 다음과 같습니다.

양호: 정의되지 않음

반환된 데이터가 수신되지 않는 이유는 무엇입니까?

도움을 주신 모든 분들께 감사드립니다.

--- 편집 갱신 ---

js를 다음과 같이 줄였습니다.

import $ from 'jquery';
$.get('http://localhost:8008/api/user')
  .done(function(data) {
    console.log(data);
  });

아직 출력으로 정의되지 않았습니다.네트워크 탭에서 요청을 열면 올바른 데이터를 가진 응답 개체를 볼 수 있습니다.요청이 이루어지고 서버가 happy하고 응답하며 결과는 브라우저에 표시되지만 done의 데이터 파라미터는 정의되지 않았습니다.나는 당황했다.

--- 업데이트 2 - 솔루션 발견 ---

CORS를 피하기 위해 https://github.com/jpillora/xdomain을 사용하는 것이 문제라는 것을 알게 되었습니다.도서관이 어떻게든 역류하는 가치를 망치는 것처럼 보일 것이다.나는 그것을 제거했고, 그것을 지원하지 않는 브라우저와 함께 CORS를 적절히 구현할 것이다.

jQuery Ajax 메서드는 약속 자체를 반환하므로 전혀 랩할 필요가 없습니다.

물론 ES6 약속 API와의 정합성을 위해 이를 수행할 수 있습니다.

UPDATE jQuery 3.0+는 Promise/A+ API를 구현하므로 더 이상 현대의 jQuery로 아무것도 랩할 필요가 없습니다.버전 3.0 이전 jQuery의 약속 구현의 특징을 읽어 보십시오.

3.0 이전 버전의 jQuery의 경우 사용자보다 더 많이 분리할 수 있습니다.

function ajax(options) {
  return new Promise(function (resolve, reject) {
    $.ajax(options).done(resolve).fail(reject);
  });
}

그리고.

ajax({
  url: someURL,
  type: 'post',
  contentType: 'application/json; charset=utf-8',
  data: JSON.stringify({
    something: something,
    anotherthing: anotherthing
  })
}).then(
  function fulfillHandler(data) {
    // ...
  },
  function rejectHandler(jqXHR, textStatus, errorThrown) {
    // ...
  }
).catch(function errorHandler(error) {
  // ...
});

언급URL : https://stackoverflow.com/questions/35135110/jquery-ajax-with-es6-promises

반응형