최대 1 분 소요

AJAX(Asynchronous Javascript And XML): 서버와 비동기적으로 데이터를 주고받는 자바스크립트 기술


1. 옛날 JS 방식

<script>
  var ajax = new XMLHttpRequest();
  ajax.onreadystatechane = function () {
    if (this.readyState == 4 && this.status == 200) {
      console.log(ajax.responseText);
    }
  };
  ajax.open("GET", "https://codingapple1.github.io/price.json", true);
  ajax.send();
</script>




2. 요즘 JS 방식

<script>
  fetch("https://codingapple1.github.io/price.json")
    .then((response) => {
      return response.json();
    })
    .then((결과) => {
      console.log(결과);
    })
    .catch(() => {
      console.log("에러남");
    });
</script>




3. async/await 방식

<script>
  async function 데이터가져오는함수() {
    var response = await fetch("https://codingapple1.github.io/price.json");
    if (!response.ok) {
      throw new Error("400 아님 500 에러남");
    }
    var result = await response.json();
    console.log(result);
  }
  데이터가져오는함수().catch(() => {
    console.log("에러남");
  });
</script>




4. axios 방식

<script>
  axios
    .get("https://codingapple1.github.io/price.json")
    .then((result) => {
      console.log(result.data);
    })
    .catch(() => {
      console.log("에러남");
    });
</script>

댓글남기기