XMLHttpRequest
서버와 상호작용하기 위하여 사용됩니다. 전체 페이지의 새로고침없이도 URL 로부터 데이터를 받아올 수 있습니다.
웹 페이지가 사용자가 하고 있는 것을 방해하지 않으면서 페이지의 일부를 업데이트할 수 있도록 해줍니다
const xhr = new XMLHttpRequest(); //인스턴스 생성
xhr.onreadystatechange = function() {
if (xhr.readyState == xhr.DONE) {
if (xhr.status === 200) {
console.log(xhr.response)
}else {
console.log("error");
}
}
}
xhr.open("GET", "https://jsonplaceholder.typicode.com/todos/1");
xhr.send();
Fetch API
네트워크 통신을 포함한 리소스 취득을 위한 인터페이스가 정의되어 있습니다. XMLHttpRequest와 같은 비슷한 API가 존재합니다만, 새로운 Fetch API는 좀더 강력하고 유연한 조작이 가능
일반적인 오브젝트로로 Request 와 Response가 포함
fetch('https://jsonplaceholder.typicode.com/todos/1')
.then(response => response.json())
.then(json => console.log(json))
1. URL fetch 요청
2. Fetch 응답 갹체를 받아옴
3. 응답 객체가 JSON => 순수 JS 객체로 변환
fetch('https://jsonplaceholder.typicode.com/todos/1')
.then(response => console.dir(response))
.then(json => console.log(json))
응답값 확인 가능
또 다른 예제 코드~
fetch('https://codingapple1.github.io/price.json')
.then((response) => {
if (!response.ok) {
throw new Error("400 아니면 500 에러남")
}
return response.json()
}).then((결과) => {
console.log(결과)
}).catch(() => {
console.log("에러남")
})
JSON.stringify()
JavaScript 값이나 객체를 JSON 문자열로 변환
JSON stringify
"JS Object" -> JSON : 서버로 데이터를 보낼 때 사용
const jsonObj = JSON.stringify({ x: 5, y: 6 });
console.log(typeof jsonObj);
console.log(jsonObj);
JSON객체는 typeof로 찍어보면 string으로 나온다.
일반 객체의 타입은 object이다.
JSON.parse()
SON 문자열의 구문을 분석하고, 그 결과에서 JavaScript 값이나 객체를 생성합니다.
JSON stringify
"JS Object" -> JSON : 서버로 데이터를 보낼 때 사용
JSON.parse()를 이용하면 object 형으로 변경 가능하다.
'웹 개발 > 기초' 카테고리의 다른 글
콜백함수 (0) | 2022.03.23 |
---|---|
[JS] 이벤트 다루기 (0) | 2022.03.22 |
자바스크립트 기본 문법 (0) | 2022.03.14 |
[css] 반응형 레이아웃 만들기 (0) | 2022.03.10 |
[CSS] flex box, grid (0) | 2022.03.07 |
자바스크립트 API 통신