일반

[Network] XMLHttpRequest란? 개념

XMLHttpRequest

이 기술 이전에는 비동기 처리를 위해서 <iframe>이나 <img>를 써서 억지로 구현은 했으나 공식적으로 나온
XMLHttpRequest는 HTTP를 통해서 쉽게 데이터를 받을 수 있게 해주는 오브젝트를 제공한다.
Ajax로 실행되는 HTTP 통신도 XMLHttpRequest 규격을 이용하고 있다.

 

사용 방법

1
2
3
4
5
var xhr = new XMLHttpRequest();
 
xhr.open('GET', 'http://localhost:3000/', true);
 
xhr.send(null);
 

위 코드를 사용하게 되면 http://localhost:3000 로 비동기로 HTTP 요청을 하게 된다.

정리하면 아래와 같다.
1. XMLHttpRequest()를 통해 오브젝트 생성을 한다.
2. 그 후 open() 함수를 통해 메소드 방식, url, 그리고 비동기 여부를 설정한다.
3. send(data) 로 설정한 방식대로 request를 보낸다.(data는 null이어도 된다.)

 

응답 방식

1
2
3
4
5
6
xhr.onreadystatechange = function()
{
    if(xhr.readyState == XMLHttpRequest.DONE && xhr.status == 200) {
        console.log(xhr.responseText);
    }
}

위 코드를 사용하게 XMLHttpRequest 오브젝트에 onreadystatechange를 등록하면 request 후 해당 server로부터 status code가 200이면 response 받은 text를 콘솔에 출력한다.

 

데이터 전송 ( Content-type 2가지 방식 소개 )

1
2
3
4
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
 
var data = 'id=' + id + '&' + 'pw' + pw;
xhr.send(data);
 

x-www-form-urlencoded로 Content-type을 지정하면 data는 form 형식을 유지해야 한다.

 

1
2
3
4
5
6
7
8
xhr.setRequestHeader('Content-Type', 'application/json');
 
var data = {
  id: id,
  pw: pw
}
 
xhr.send(data);
 

Content-type이 application/json 타입이면 data는 json 타입이어야 한다.

 

푸터바