쑤쑤_CS 기록장

35. 비동기식 처리 모델과 Ajax 본문

IT 지식 기록/JavaScript 정리

35. 비동기식 처리 모델과 Ajax

(╹◡╹)_ 2020. 12. 28. 17:27
728x90

#1. Ajax (Asynchronous JavaScript and XML)

  • 브라우저에서 웹페이지를 요청하거나 링크를 클릭하면 화면 갱신이 발생한다.
    이는 브라우저와 서버와의 통신에 의한 것이다.

  • 서버로부터 웹페이지가 반환되면 클라이언트(브라우저)는 이를 렌더링하여 화면에 표시한다.

     

  • Ajax(Asynchronous JavaScript and XML)
    : 자바스크립트를 이용해서
    비동기적(Asynchronous)으로 서버와 브라우저가 데이터를 교환할 수 있는 통신 방식
  • 서버로부터 웹페이지가 반환되면 화면 전체를 갱신하지 않고, 페이지 일부만을 갱신하여 동일한 효과를 볼 수 있도록 한다.
    • 페이지 전체를 로드하여 렌더링 할 필요가 없고, 갱신이 필요한 일부만 로드하여 갱신한다
    • 빠른 퍼포먼스와 부드러운 화면 표시효과를 기대할 수 있다.

#2. JSON (JavaScript Object Notation)

: 클라이언트와 서버 간 데이터 교환을 위한 규칙. 데이터 포맷.

  • 일반 텍스트 포맷보다 효과적인 데이터 구조화 가능
  • XML 포맷보다 가볍고 사용하기 간편, 가독성이 좋다
  • 순수한 텍스트로 구성된 규칙이 있는 데이터 구조
  • 키는 반드시 큰따옴표로 둘러싸야 한다. (작은따옴표 사용 불가)
{
  "name": "Lee",
  "gender": "male",
  "age": 20,
  "alive": true
}

#2.1 JSON.stringify

  • 객체를 JSON 형식의 문자열로 변환
const o = { name: 'Lee', gender: 'male', age: 20 };

// 객체 => JSON 형식의 문자열
const strObject = JSON.stringify(o);
console.log(typeof strObject, strObject);
// string {"name":"Lee","gender":"male","age":20}

// 객체 => JSON 형식의 문자열 + prettify
const strPrettyObject = JSON.stringify(o, null, 2);
console.log(typeof strPrettyObject, strPrettyObject);
/*
string {
  "name": "Lee",
  "gender": "male",
  "age": 20
}
*/

// replacer
// 값의 타입이 Number이면 필터링되어 반환되지 않는다.
function filter(key, value) {
  // undefined: 반환하지 않음
  return typeof value === 'number' ? undefined : value;
}

// 객체 => JSON 형식의 문자열 + replacer + prettify
const strFilteredObject = JSON.stringify(o, filter, 2);
console.log(typeof strFilteredObject, strFilteredObject);
/*
string {
  "name": "Lee",
  "gender": "male"
}
*/

const arr = [1, 5, 'false'];

// 배열 객체 => 문자열
const strArray = JSON.stringify(arr);
console.log(typeof strArray, strArray); // string [1,5,"false"]

// replacer
// 모든 값을 대문자로 변환된 문자열을 반환한다
function replaceToUpper(key, value) {
  return value.toString().toUpperCase();
}

// 배열 객체 => 문자열 + replacer
const strFilteredArray = JSON.stringify(arr, replaceToUpper);
console.log(typeof strFilteredArray, strFilteredArray); // string "1,5,FALSE"

#2.2 JSON.parse

  • JSON 데이터를 가진 문자열을 객체로 변환
const o = { name: 'Lee', gender: 'male', age: 20 };

// 객체 => JSON 형식의 문자열
const strObject = JSON.stringify(o);
console.log(typeof strObject, strObject);
// string {"name":"Lee","gender":"male","age":20}

const arr = [1, 5, 'false'];

// 배열 객체 => 문자열
const strArray = JSON.stringify(arr);
console.log(typeof strArray, strArray); // string [1,5,"false"]

// JSON 형식의 문자열 => 객체
const obj = JSON.parse(strObject);
console.log(typeof obj, obj); // object { name: 'Lee', gender: 'male' }

// 문자열 => 배열 객체
const objArray = JSON.parse(strArray);
console.log(typeof objArray, objArray); // object [1, 5, "false"]

#3. XMLHttpRequest

  • XMLHttpRequest 객체를 이용하여 Ajax 요청을 생성하고 전송한다.

  • 서버가 브라우저의 요청에 응답을 반환하면 같은 XMLHttpRequest 객체가 결과를 처리한다.

#3.1 Ajax request

// XMLHttpRequest 객체의 생성
const xhr = new XMLHttpRequest();
// 비동기 방식으로 Request를 오픈한다
xhr.open('GET', '/users');
// Request를 전송한다
xhr.send();

#3.1.1 XMLHttpRequest.open

  • XMLHttpRequest 객체의 인스턴스를 생성

  • XMLHttpRequest.open 메소드를 사용하여 서버로의 요청을 준비

XMLHttpRequest.open(method, url[, async])

- method : HTTP method (“GET”, “POST”, “PUT”, “DELETE” 등)

- url : 요청을 보낼 URL

- async : 비동기 조작 여부. 옵션으로 default는 true이며 비동기 방식으로 동작한다.

#3.1.2 XMLHttpRequest.send

  • send 메소드로 준비된 요청을 서버에 전달

  • GET 메소드 : URL의 일부분인 쿼리문자열로 데이터를 서버로 전송한다.
  • POST 메소드 : 데이터(페이로드)를 Request Body에 담아 전송한다.
  • request body에 담아 전송할 인수를 전달할 수 있다

     

#3.1.3 XMLHttpRequest.setRequestHeader

  • HTTP Request Header의 값을 설정

  • 반드시 XMLHttpRequest.open 메소드 호출 이후에 호출한다.

  • 자주 사용하는 Request Header

    • Content-type

      • request body에 담아 전송할 데이터의 MIME-type의 정보를 표현

    •  

      Accept

      • HTTP 클라이언트가 서버에 요청할 때 서버의 데이터 MIME-type을 Accept로 지정

         

#3.2 Ajax response

// XMLHttpRequest 객체의 생성
const xhr = new XMLHttpRequest();

// XMLHttpRequest.readyState 프로퍼티가 변경(이벤트 발생)될 때마다 onreadystatechange 이벤트 핸들러가 호출된다.
xhr.onreadystatechange = function (e) {
  // readyStates는 XMLHttpRequest의 상태(state)를 반환
  // readyState: 4 => DONE(서버 응답 완료)
  if (xhr.readyState !== XMLHttpRequest.DONE) return;

  // status는 response 상태 코드를 반환 : 200 => 정상 응답
  if(xhr.status === 200) {
    console.log(xhr.responseText);
  } else {
    console.log('Error!');
  }
};
  • XMLHttpRequest.onreadystatechange

    • Response가 클라이언트에 도달하면 발생된 이벤트를 감지하고 콜백 함수를 실행
    • Request에 변화 발생한 경우 ( XMLHttpRequest.readyState 프로퍼티 변경시 발생 ) 이벤트가 발생한다.

#4. Web Server

웹서버(Web Server)

: 브라우저와 같은 클라이언트로부터 HTTP 요청을 받아들이고 HTML 문서와 같은 웹 페이지를 반환하는 컴퓨터 프로그램이다.

728x90
Comments