Modern JavaScript Deep Dive 스터디 - CH43 Ajax
참고 자료: ⟪모던 자바스크립트 Deep Dive⟫(이웅모 지음,위키북스, 2020)
Asynchronous JavaScript and XML
의 약자Ajax 이전의 통신 방식
HTML 문서 통째를 서버로 전달 받아 웹페이지를 처음부터 다시 렌더링 하는 방식으로 동작하였다. 따라서 불필요한 데이터 통신이 발생하고, 클라이언트와 서버와의 통신이 동기 방식으로 동작하기 때문에 서버로부터 응답이 있을 때까지 다음 처리는 블로킹되었다.
JavaScript Object Notation
의 약자{
"name": "Boo",
"age": 27,
"student": false,
"hobby": ["running", "game"]
}
const obj = {
name: 'Lee',
age: 20,
alive: true,
hobby: ['traveling', 'tennis'],
};
// 객체를 JSON 포맷의 문자열로 변환한다.
const json = JSON.stringify(obj);
console.log(typeof json, json);
// string {"name":"Lee","age":20,"alive":true,"hobby":["traveling","tennis"]}
// 객체를 JSON 포맷의 문자열로 변환하면서 들여쓰기 한다.
const prettyJson = JSON.stringify(obj, null, 2);
console.log(typeof prettyJson, prettyJson);
/*
string {
"name": "Lee",
"age": 20,
"alive": true,
"hobby": [
"traveling",
"tennis"
]
}
*/
// replacer 함수. 값의 타입이 Number이면 필터링되어 반환되지 않는다.
function filter(key, value) {
// undefined: 반환하지 않음
return typeof value === 'number' ? undefined : value;
}
// JSON.stringify 메서드에 두 번째 인수로 replacer 함수를 전달한다.
const strFilteredObject = JSON.stringify(obj, filter, 2);
console.log(typeof strFilteredObject, strFilteredObject);
/*
string {
"name": "Lee",
"alive": true,
"hobby": [
"traveling",
"tennis"
]
}
*/
const obj = {
name: 'Lee',
age: 20,
alive: true,
hobby: ['traveling', 'tennis'],
};
// 객체를 JSON 포맷의 문자열로 변환한다.
const json = JSON.stringify(obj);
// JSON 포맷의 문자열을 객체로 변환한다.
const parsed = JSON.parse(json);
console.log(typeof parsed, parsed);
// object {name: "Lee", age: 20, alive: true, hobby: ["traveling", "tennis"]}
// XMLHttpRequest 객체 생성
const xhr = new XMLHttpRequest();
프로토타입 프로퍼티
- readyState: HTTP 요청의 현재 상태를 나타내는 정수
- UNSENT: 0
- OPENED: 1
- HEADERS_RECEIVED: 2
- LOADING: 3
- DONE: 4
- status : HTTP 상태 코드. ex) 200, 300, 400, ...
- statusText: HTTP 요청에 대한 응답 메시지를 나타내는 문자열. ex) "OK"
- responseType: HTTP 응답 타입. ex) document, json, text, blob, arraybuffer
- response: HTTP 요청에 대한 응답 몸체. responseType에 따라 타입이 다름
이벤트 핸들러 프로퍼티
- onload : HTTP 요청이 성공적으로 완료한 경우
- onerror : HTTP 요청에 에러가 발생한 경우
- onreadystatechange: readyState 프로퍼티 값이 변경된 경우
메서드
- open : HTTP 요청 초기화
- send : HTTP 요청 전송
- abort: 이미 전송된 HTTP 요청 중단
- setRequestHeader : 헤더 설정
(1) XMLHttpRequest.prototype.open 메서드로 HTTP 요청을 초기화한다.
(2) 필요에 따라 XMLHttpRequest.prototype.setRequestHeader 메서드로 특정 HTTP 요청의 헤더 값을 설정한다.
(3) XMLHttpRequest.prototype.send 메서드로 HTTP 요청을 전송한다.
// XMLHttpRequest 객체 생성
const xhr = new XMLHttpRequest();
// HTTP 요청 초기화
xhr.open('GET', '/users');
// HTTP 요청 헤더 설정
// 클라이언트가 서버로 전송할 데이터의 MIME 타입 지정: json
xhr.setRequestHeader('content-type', 'application/json');
// HTTP 요청 전송
xhr.send();
// XMLHttpRequest 객체 생성
const xhr = new XMLHttpRequest();
// HTTP 요청 초기화
// https://jsonplaceholder.typicode.com은 Fake REST API를 제공하는 서비스다.
xhr.open('GET', 'https://jsonplaceholder.typicode.com/todos/1');
// HTTP 요청 전송
xhr.send();
// load 이벤트는 HTTP 요청이 성공적으로 완료된 경우 발생한다.
xhr.onload = () => {
// status 프로퍼티는 응답 상태 코드를 나타낸다.
// status 프로퍼티 값이 200이면 정상적으로 응답된 상태이고
// status 프로퍼티 값이 200이 아니면 에러가 발생한 상태다.
// 정상적으로 응답된 상태라면 response 프로퍼티에 서버의 응답 결과가 담겨 있다.
if (xhr.status === 200) {
console.log(JSON.parse(xhr.response));
// {userId: 1, id: 1, title: "delectus aut autem", completed: false}
} else {
console.error('Error', xhr.status, xhr.statusText);
}
};
혹시 인하대이신가요?