동기 통신 실습
콘솔에 데이터 출력  
<!DOCTYPE html>
<html lang="ko-KR">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Ajax 비동기 통신</title>
</head>
<body>
  <p class="print_area"></p>
  <script src="./action.js"></script>
</body>
</html>;(function (global) {
  'use strict'
  // XMLHttpRequest 객체 생성
  var xhr = new XMLHttpRequest()
  // .open() 메서드 동기 통신 설정
  xhr.open('GET', './ajax-desc.txt', false)
  // 서버에 요청
  xhr.send()
  // 동기 통신에 따른 응답이 오면 처리
  if (xhr.status === 200) {
    console.log(xhr, xhr.responseText)
  }
})(window)
에이젝스(Ajax)란? JavaScript와 XML 또는 JSON을 사용해 
비동기 통신 방법으로 웹 애플리케이션을 제작하는 것을 말합니다. 
간단히 말하면 서버측 Scripts와 통신하기 위한 XMLHttpRequest객체를 사용하는 것을 말합니다.

버튼 클릭 시 콘솔에 데이터 출력 
<!DOCTYPE html>
<html lang="ko-KR">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Ajax 비동기 통신</title>
</head>
<body>
  <!-- 버튼 추가 -->
  <button type="button" class="call-ajax-data-button">서버에 데이터 요청</button>
  <p class="print_area"></p>
  <script src="./action.js"></script>
</body>
</html>;(function (global) {
  'use strict'
  var xhr = new XMLHttpRequest()
  xhr.open('GET', './ajax-desc.txt', false)
  var call_btn = document.querySelector('.call-ajax-data-button')
  var callAjaxData = function () {
    // 클릭 시 데이터 전송 
    xhr.send()
    // 200과 304번일 때 데이터 출력 
    if (xhr.status === 200 || xhr.status === 304) {
      console.log(xhr, xhr.responseText)
    } else {
      // 경고 메세지 출력 
      console.worn('통신 실패')
    }
  }
// 버튼에 클릭 이벤트 바인딩 
  call_btn.addEventListener('click', callAjaxData)
})(window)버튼을 클릭 했을 때, 콘솔에 텍스트가 잘 출력되는 것을 확인 할 수 있다.

이 때, 텍스트 파일의 통신 상태를 보면 304번인 것을 알 수 있다. 이 것은 상단에 실습을 했을 때와 이번에 버튼을 추가하고 실습을 했을 때의 텍스트 데이터에 변경 사항이 없기 때문이다. 즉, 변경이 되지 않았다는 것이다.


버튼 클릭 시 브라우저에 데이터 출력  
;(function (global) {
  'use strict'
  var xhr = new XMLHttpRequest()
  xhr.open('GET', './ajax-desc.txt', false)
  var call_btn = document.querySelector('.call-ajax-data-button')
  var print_area = document.querySelector('.print_area') // 단락요소 
  
  var callAjaxData = function () {
    xhr.send()
    if (xhr.status === 200 || xhr.status === 304) {
      // 단락 요소에 데이터 텍스트가 삽입되도록 설정 
      print_area.textContent = xhr.responseText
    } else {
      console.warn('통신 실패')
    }
  }
  call_btn.addEventListener('click', callAjaxData)
})(window)

Last updated
Was this helpful?