Asynchronous Javscript And XML
비동기적 웹 서비스를 개발하기 위한 기법
xml이 들어가 있지만 요즘은 JSON 사용
페이지 이동(전환) 없이 서버에 요청 보내고 응답 받는 기술보통 Ajax 요청은 jQuery나 axios 같은 라이브러리를 이용해 보낸다.
<script> var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function(){ // 요청에 대한 콜백 if(xhr.readyState === xhr.Done) { // 요청이 완료되면 console.log(xhr.responseText); // 서버에서 보내주는 값 }else{ console.error(xhr.responseText); } }; xhr.open('GET','https://주소'); // 메서드와 주소 설정 xhr.send(); // 요청 전송 </script>먼저 XmlHttpRequest 생성자로 xhr 객체 생성
xhr.open 메서드에 요청 메서드와 요청 주소를 넣고 xhr.send 메서드를 보내면 된다.
xhr.onreadyStateChange 는 이벤트 리스너로 요청 후 서버로 부터 응답이 올때 응답 받을 수 있다.
응답 코드가 200번대면 성공 아니면 에러
onreadystatechange 대신 onload와 onerror로 성공과 실패를 구분해도 된다.var xhr = new XMHttpRequest(); xhr.onload = function(){ // 요청에 대한 콜백 if(xhr.status === 200 || xhr.status === 201) { // 요청이 완료되면 console.log(xhr.responseText); // 서버에서 보내주는 값 } }; xhr.onerror = function(){ console.log(xhr.responseText); }; xhr.open('GET','https://도메인주소'); // 메서드와 주소 설정 xhr.send() // 요청 전송
Post 경우 (서버로 데이터를 보내는 Post)
Json 데이터를 보낸다.
<script> var xhr = new XMLHttpRequest(); var data - { name = 'rickter', Month: 03 }; xhr.onreadystatechange = function(){ if(xhr.readyState === xhr.DONE){ if(xhr.status == 200 || xhr.status === 201){ console.log(xhr.responseText); }else{ console.eror(xhr.responseText); } } }; xhr.open('GET','https://도메인주소'); xhr.setRequestHeader('Content-Type','application/json'); // 콘텐츠 타입을 json으로 xhr.send(JSON.stringify(data)); // 데이터 동봉해 전송 </script>
xhr.setRequestHeader 메서드로 서버로 보내는 컨텐츠가 JSON형식임을 알릴 수 있다.