전통적인 방식
Ajax 방식
{
"name": "Lee",
"gender": "male",
"age": 20,
// ✖️작은 따옴표✖️
'alive': true
}
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
}
*/
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 형식의 문자열 => 객체
const obj = JSON.parse(strObject);
console.log(typeof obj, obj);
// object { name: 'Lee', gender: 'male' }
// XMLHttpRequest 객체의 생성
const xhr = new XMLHttpRequest();
// 비동기 방식으로 Request를 오픈한다
xhr.open('GET', 'url');
// Request를 전송한다
xhr.send();
xhr.open( method, url [ ,async ] )
method
: HTTP method ("GET","POST","PUT","DELETE")url
: 요청을 보낼 URLasync
: 비동기 조작 여부, 옵션으로 default는 true이며 비동기방식으로 동작함xhr.send( )
GET
: URL의 일부분인 쿼리문자열로 데이터를 서버로 전송POST
: 데이터(페이로드)를 Request Body에 담아 전송💡 xhr.setResquestHeader
xhr.open()
호출 이후에 호출한다.*/*
으로 전송// json으로 전송하는 경우
xhr.open('POST', '/users');
// 클라이언트가 서버로 전송할 데이터의 MIME-type 지정: json
xhr.setRequestHeader('Content-type', 'application/json');
const data = { id: 3, title: 'JavaScript', author: 'Park', price: 5000};
xhr.send(JSON.stringify(data));
// 서버가 센드백할 데이터의 MIME-type 지정: json
xhr.setRequestHeader('Accept', 'application/json');
xhr.send()
를 통해 서버 Request를 전송하면xhr.onreadystateChange
는 Response까 클라이언트에 도달하여 발생된 이벤트를 감지하고 콜백함수를 실행xhr.readyState
프로퍼티가 변경된 경우 발생xhr.readyState
: XMLHttpRequset 객체는 response가 클라이언트에 도달했는지를 추적할 수 있는 프로퍼티를 제공// XMLHttpRequest 객체의 생성
var xhr = new XMLHttpRequest();
// 비동기 방식으로 Request를 오픈한다
xhr.open('GET', 'data/test.json');
// Request를 전송한다
xhr.send();
// XMLHttpRequest.readyState 프로퍼티가 변경(이벤트 발생)될 때마다 콜백함수(이벤트 핸들러)를 호출한다.
xhr.onreadystatechange = function (e) {
// 이 함수는 Response가 클라이언트에 도달하면 호출된다.
// 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!');
}
};
xhr.readyState
가 4인 경우, 서버 응답 완료 상태이므로 이후xhr.status
가 200(정상응답)을 확인하고xhr.responseText
를 취득load
이벤트를 사용해도 된다.// XMLHttpRequest 객체의 생성
var xhr = new XMLHttpRequest();
// 비동기 방식으로 Request를 오픈한다
xhr.open('GET', 'data/test.json');
// Request를 전송한다
xhr.send();
// load 이벤트는 서버 응답이 완료된 경우에 발생한다.
xhr.onload = function (e) {
// status는 response 상태 코드를 반환 : 200 => 정상 응답
if(xhr.status === 200) {
console.log(xhr.responseText);
} else {
console.log('Error!');
}
};
{
"tours": [
{
"region": "usa",
"location": "New York, USA",
"details": "$1,899 for 7 nights"
},
{
"region": "europe",
"location": "Paris, France",
"details": "$2,299 for 7 nights"
},
{
"region": "asia",
"location": "Tokyo, Japan",
"details": "$3,799 for 7 nights"
}
]
}
<!-- 루트 폴더(webserver-express/public)/loadjson.html -->
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="https://poiemaweb.com/assets/css/ajax.css">
</head>
<body>
<div id="content"></div>
<script>
// XMLHttpRequest 객체의 생성
var xhr = new XMLHttpRequest();
// 비동기 방식으로 Request를 오픈한다
xhr.open('GET', 'data/data.json');
// Request를 전송한다
xhr.send();
xhr.onreadystatechange = function () {
// 서버 응답 완료 && 정상 응답
if (xhr.readyState !== XMLHttpRequest.DONE) return;
if (xhr.status === 200) {
console.log(xhr.responseText);
// Deserializing (String → Object)
responseObject = JSON.parse(xhr.responseText);
// JSON → HTML String
let newContent = '<div id="tours"><h1>Guided Tours</h1><ul>';
responseObject.tours.forEach(tour => {
newContent += `<li class="${tour.region} tour">
<h2>${tour.location}</h2>
<span class="details">${tour.details}</span>
<button class="book">Book Now</button>
</li>`;
});
newContent += '</ul></div>';
document.getElementById('content').innerHTML = newContent;
} else {
console.log(`[${xhr.status}] : ${xhr.statusText}`);
}
};
</script>
</body>
</html>