AJAX 비동기

Hvvany·2022년 11월 23일
0

Javascript

목록 보기
2/12

AJAX

Asyncronous Javascript and XML

비동기식 자바스크립트, xml
전체 화면 새로고침 없이 서버에 요청을 보내고 일부분만 새로 고침.

axios 라이브러리를 통해 쉽게 구현 가능. 요즘은 xml보다는 json을 사용.

axios

promise 기반의 클라이언트

원래는 “XHR”이라는 브라우저 내장 객체를 활용해 AJAX 요청을 처리하는데, 이보다 편리한 AJAX 요청이 가능하도록 도움을 줌

1. axios 방식

<body>
  <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
  <script>
    const URL = 'https://jsonplaceholder.typicode.com/todos/1'
    axios.get(URL)
      .then(response => console.log(response.data))
      .catch(err => console.log('${err}!!!'))
    console.log('안녕하세요')
  </script>
</body>

2. xml xhr 방식

버튼으로 새로고침 없이 데이터 연속으로 가져오기

<script>
    const body = document.querySelector('body')
    const title = document.createElement('h1')
    title.innerText = '아작스'
    body.appendChild(title)

    const button = document.querySelector('button')
    button.addEventListener('click', function(){
      const URL = 'https://jsonplaceholder.typicode.com/todos/1'
      axios.get(URL)
        .then(response => {
          const h2 = document.createElement('h2')
          h2.innerText = response.data.title
          body.appendChild(h2)
          const p = document.createElement('p')
          p.innerText = response.data.userId
          body.appendChild(p)
        })
        .catch(err => console.log('${err}!!!'))
    } )
  </script>

(참고)자바스크립트 구문 정리

/* body 라는 변수에 문서에서 body태그를 찾아서 넣어준다 */
const body = document.querySelector('body')

/* h1 태그를 생성하여 title변쉬에 넣어준다 */
const title = document.createElement('h1')

/* title의 내부 문구로 '아작스'를 넣습니다 */
title.innerText = '아작스'

/* body 변수의 자식 요소로 title을 둡니다. */
body.appendChild(title)

/* button을 클릭할 때 함수 실행 */
button.addEventListener('click', function(){
  
/* axios로 url을 통해 get한다 */
axios.get(URL)
  
/* 이상 없으면 실행한다. */
.then(response => {
  

/* 화살표 함수 정리 */
  // 이 문장은 배열을 반환함: [8, 6, 7, 9]
  elements.map(function(element) {
    return element.length;
  });
  // 위의 일반적인 함수 표현은 아래 화살표 함수로 쓸 수 있다.
  elements.map((element) => {
    return element.length;
  }); // [8, 6, 7, 9]

/* jquery를 활용하여 오류 응답을 표현 */
.catch(err => console.log(`${err}!!!`))

profile
Just Do It

0개의 댓글