AJAX ( Asynchronous JavaScript And XML )
자바스크립트를 이용하여 비동기적으로 서버와 브라우저가 데이터를 교환할 수 있는 통신방식이다.
서버와 통신하기 위해 XMLHttpRequest 객체를 사용한다.
JSON, XML, HTML, 일반 텍스트 형식 등을 포함한 다양한 포맷을 주고 받을 수 있다.
비동기 전송방식(비동기식 처리모델)
병렬적인 테스크를 수행한다.
화면이 종료되지 않더라도 대기하지 않고 다음 작업을 수행한다.
(이벤트핸들러, Timer, Ajax)
사용자의 이벤트가 있으면 전체 페이지의 새로고침이 아닌 일부분만 갱신할 수 있게 해준다.
XMLHttpRequest ( XHR )
서버와 상호작용할 때 사용하며, XHR을 사용하면 페이지의 새로고침 없이도 URL에서 데이터를 가져올 수 있다.
XML 뿐만 아니라 모든 종류의 데이터를 가져올 수 있다.
const xhr = new XMLHttpRequest(); //객체 생성
xhr.open('GET', 'js/test.json'); //비동기 방식 open
xhr.setRequestHeader('Content-type', 'application/json') //MIME-type 지정
xhr.send(); //전송
xhr.onload = function(){
if(xhr.status===200){ //status = response 상태 코드 반환 : 200 정상응답
console.log(xhr.responseText);
}
}
XMLHttpRequest.open(method, URL(, async)
method : HTTP method (GET, POST 등)
URL : 주소 또는 파일명
async : default는 true이며 비동기 방식, false는 동기 방식
XMLHttpRequest.send
요청을 전송한다. 비동기 요청인 경우 send는 요청을 전송하는 즉시 반환한다.
- GET의 경우, URL의 일부분인 쿼리스트링으로 데이터를 서버로 전송하며 send메서드 안의 파라미터값은 무시된다.
- POST의 경우, 데이터를 Request Body에 담아 전송한다.
XMLHttpRequest.setRequestHeader
HTTP Request Header의 값을 설정한다.
반드시 open의 뒤에, send의 앞에 호출해야한다.
Content-type
전송할 데이터의 MIME type의 정보를 표현한다.
https://developer.mozilla.org/ko/docs/Web/HTTP/Basics_of_HTTP/MIME_types
1. text타입 : txet/plain, text/html, text/css, text/javascript
2. Application타입 : application/json, application/x-www-form-urlencode
3. File을 업로드하기 위한 타입 : multipart/formed-data
Accept
HTTP 클라이언트가 서버에 요청할 때 서버가 샌드 백 할 데이터의 MIME-type을 Accept로 지정할 수 있다.
Accept헤더를 설정하지 않으면 send 메서드가 호출될 때 Accept 헤더가 */*로 전송된다.
// 서버가 샌드 백 할 데이터의 MIME-type 지정: json
xhr.setRequestHeader('Accept', 'application/json');
XMLHttpRequest.readyState
XMLHttpRequest 객체의 현재 상태
const xhr = new XMLHttpRequest();
console.log('UNSENT', xhr.readyState); // readyState = 0
xhr.open('GET', '/api', true);
console.log('OPENED', xhr.readyState); // readyState = 1
xhr.onprogress = () => {
console.log('LOADING', xhr.readyState); // readyState = 3
};
xhr.onload = () => {
console.log('DONE', xhr.readyState); // readyState = 4
};
xhr.send(null);
값 | 상태 | 설명 |
0 | UNSET | XMLHttpRequest.open() 메서드 호출 이전 |
1 | OPENED | XMLHttpRequest.open() 메서드 호출 완료 |
2 | HEADERS_RECEIVED | XMLHttpRequest.send() 메서드 호출 완료 |
3 | LOADING | 서버 응답 중 |
4 | DONE | 서버 응답 완료 |
status
서버의 문서 상태를 표현한다(200 : 존재 / 404 : 미존재)
onreadystatechange
readyState의 프로퍼티 값이 변할 때 마다 자동으로 호출되는 함수 설정
JSON ( JavaScript Object Notation )
클라이언트와 서버 간 데이터 교환을 위한 규칙(데이터 포맷)
일반적인 텍스트 포맷보다 효과적인 데이터 구조화가 가능하다.
가볍고 가독성이 좋다.
자바스크립트의 객체 리터럴과 매우 흡사하지만 순수한 텍스트로 구성된 규칙이 있는 데이터 구조이다.
//Key Value형태이며 Key값은 반드시 큰따옴표를 사용해야 한다
{
"name": "Lee",
"gender": "male",
"age": 20,
"alive": true
}
//JSON을 가져오는 예시
//1. JSON URL을 가져온다
var requestURL = 'https://mdn.github.io/learning-area/javascript/oojs/json/superheroes.json';
//2. XHR 인스턴스 생성
var request = new XMLHttpRequest();
//3. 요청하기
request.open('GET', requestURL);
//4. 요청 보내기
request.responseType = 'json';
request.send();
//5. 서버의 응답 대기 및 처리
request.onload = function() {
var superHeroes = request.response;
populateHeader(superHeroes);
showHeroes(superHeroes);
}
//위의 단계에서 JSON데이터를 자바스크립트 객체로 변환했다.
//6. 활용하기
function populateHeader(jsonObj) {
var myH1 = document.createElement('h1');
myH1.textContent = jsonObj['squadName'];
header.appendChild(myH1);
var myPara = document.createElement('p');
myPara.textContent = 'Hometown: ' + jsonObj['homeTown'] + ' // Formed: ' + jsonObj['formed'];
header.appendChild(myPara);
}
JSON.stringify()
객체를 JSON 문자열로 변환한다.
console.log(JSON.stringify({ x: 5, y: 6 }));
//'{"x":5,"y":6}"
console.log(JSON.stringify([new Number(3), new String('false'), new Boolean(false)]));
//"[3,"false",false]"
console.log(JSON.stringify({ x: [10, undefined, function(){}, Symbol('')] }));
//"{"x":[10,null,null,null]}"
console.log(JSON.stringify(new Date(2006, 0, 2, 15, 4, 5)));
//""2006-01-02T15:04:05.000Z""
JSON.parse()
JSON 데이터를 가진 문자열을 객체로 변환한다.
const json = '{"result":true, "count":42}';
const obj = JSON.parse(json);
console.log(obj.count);
//42
console.log(obj.result);
//true
https://developer.mozilla.org/ko/docs/Learn/JavaScript/Objects/JSON
https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify
https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse
https://developer.mozilla.org/ko/docs/Web/API/XMLHttpRequest
2023.04 ~ 백엔드 개발자의 기록
포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!