0%

210126_TIL(Ajax, REST API)

오늘 배운 것

Ajax

과거 전통적인 웹페이지는 서버에서 완전한 HTML 파일을 보내주면 다시 랜더링을 진행한다.

현재는 웹 어플리케이션에서 header, footer 등 바뀌지 않는 부분은 새로 랜더링하지 않는 방식을 Ajax를 통해서 구현하였다. 웹 페이지는 아직 전통적인 방식을 사용 중이다.

Json

서버통신을 위한 데이터 포멧이다.

REST API

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
const get = (url) => {
const xhr = new XMLHttpRequest();

xhr.open("GET", url);
// xhr.setRequestHeader('content-type', 'application/json');
xhr.send();

xhr.onload = () => {
if (xhr.status === 200 || xhr.status === 201) {
console.log(JSON.parse(xhr.response));
} else {
console.error(xhr.status);
}
};
};

const post = (url, payload) => {
const xhr = new XMLHttpRequest();

xhr.open("POST", url);
xhr.setRequestHeader("content-type", "application/json");
xhr.send(JSON.stringify(payload));

xhr.onload = () => {
if (xhr.status === 200 || xhr.status === 201) {
console.log(JSON.parse(xhr.response));
} else {
console.error(xhr.status);
}
};
};

const patch = (url, payload) => {
const xhr = new XMLHttpRequest();

xhr.open("PATCH", url);
xhr.setRequestHeader("content-type", "application/json");
xhr.send(JSON.stringify(payload));

xhr.onload = () => {
if (xhr.status === 200 || xhr.status === 201) {
console.log(JSON.parse(xhr.response));
} else {
console.error(xhr.status);
}
};
};

const remove = (url) => {
const xhr = new XMLHttpRequest();

xhr.open("DELETE", url);
// xhr.setRequestHeader('content-type', 'application/json');
xhr.send();

xhr.onload = () => {
if (xhr.status === 200 || xhr.status === 201) {
console.log(JSON.parse(xhr.response));
} else {
console.error(xhr.status);
}
};
};

get("/todos/2");
post("/todos", { id: 4, content: "React", completed: false });
patch("/todos/4", { completed: true });
remove("/todos/4");

Nyong’s GitHub