본문 바로가기
Javascript

Ajax with XHR

by kmmguumnn 2018. 7. 3.

Ajax



AJAX는 "Asynchronous Javascript and XML"의 약자다.


그러나 최근에는 XML 뿐만 아니라 수많은 데이터 형태들(Javascript, JSON, html 등)을 모두 뜻하며, 

"어떤 데이터를 비동기적(Asynchronous)으로 요청하고, 요청이 돌아오면 그 데이터를 활용"하는 것으로 이해하면 된다.

사실 최근에는 XML보다는 JSON이 훨씬 많이 쓰여서, AJAJ라고 하는 게 더 맞는 것 같기도 하다(물론 실제로 그렇게 부르진 않지만).


AJAX의 Asynchronous, 즉 비동기라는 것은, "요청이 다른 이벤트의 발생을 막지(block) 않는다"는 뜻이다.

대신, 페이지는 하던 일을 계속 하고, 서버로부터 응답으로 받은 데이터를 사용하게 된다.


만약 클라이언트가 동기적으로 요청한다면(AJAX 없이), 응답이 돌아올 때까지 아무것도 하지 않고 그냥 기다려야 한다.

반면 AJAX는 이러한 요청들을 비동기적으로 처리한다. 즉, 나머지 페이지의 로딩을 막지 않은 채, 백그라운드에서 요청들을 처리할 수 있는 것이다.


다음의 상황을 가정해 보자.

클라이언트가 서버에게 GET 요청을 보내면서, 콜백, 즉 응답이 돌아오면 그것을 바탕으로 하게 될 일을 지정한다.

이 때 서버가 요청을 처리하는 동안, 클라이언트는 다른 일을 자유롭게 처리할 수 있다. 

그러다가 서버로부터 응답이 돌아오게 되면, 그 때 클라이언트가 콜백을 처리하게 된다.

서버가 보내주는 응답에는 클라이언트가 페이지의 내용을 load하는 데 필요한 데이터가 포함돼 있다.


Client Server Demonstration - Intro to AJAX on YouTube by Udacity 참조





History


Up until the mid-2000s, this was basically the only way internet communication occurred. Information would reside on the server, and a client would request that data and refresh the page and display it. This cycle would repeat for each and every new page request.


In the late 90s, the Microsoft Outlook team added the XMLHTTP component to Internet Explorer and built a web version of the Outlook mail client. This code was later picked up by other browsers as XMLHttpRequest. This allowed browsers to make HTTP requests from Javascript and update the current page in place without fetching an entire page from the server. Instead of the synchronous model of waiting for a whole page, the user interface could update asynchronously as the user kept working. Most of the data being exchanged used the XML format.


AJAX

In 2005, Jesse James Garrett coined the term AJAX to mean “Asynchronous Javascript and XML”. This is essentially the technique of using XMLHttpRequest to fetch data and then modify the current page.


AJAX took the web world by storm, spreading far beyond Microsoft Outlook. State-of-the-art web applications like Flickr, Gmail, and Google Maps rapidly adopted it. Instead of having to wait for data and have the entire page refresh, these new, near instantaneous applications were incredible.





XHR


XHR(XML Http Request) object는 JavaScript 환경에 의해 제공되고, Ajax 요청(request), 즉 비동기 요청을 만드는 데 사용된다.


JavaScript engine은 비동기 HTTP 요청을 만들기 위한 방법을 제공하는데, XMLHttpRequest object가 바로 그것이다. 기본적으로 제공되는 XMLHttpRequest constructor function을 사용하면 된다.

위에서도 썼듯이, AJAX의 X는 곧 XML의 X이다. 하지만 XMLHttpRequest(XHR)는 꼭 XML 뿐만 아니라 수많은 데이터들(plain text files, HTML files, JSON files, image files 등)을 API로부터 받아오는 데 사용된다. 이름은 XMLHttpRequest라고 되어있지만 꼭 XML일 필요가 없다.




Asynchoronous request 보내기


XMLHttpRequest.open() (링크 참조)

ex) asyncRequestObject.open('GET', 'https://unsplash.com');


사실 open()은 실제로 요청을 보내지는 않는다. 실제 요청이 보내질 때 필요한 정보들을 XMLHttpRequest 객체에 전달(initialize)하는 역할을 한다.

만약 세번째 argument로 false를 주게 되면, 동기적(synchronous; pause and wait; blocking)으로 요청하게 된다. 하지만 이렇게 되면 XHR을 하는 의미가 없어진다. false는 절대 쓰지 않는다.


open을 해준 뒤 .send()를 호출해야 실제 XHR 요청을 보내게 된다.


또한, 요청이 성공적일 때와 실패했을 때 어떤 처리를 하게 될지를 지정할 수 있는데, 이 때 'onload' property와 'onerror' property를 사용한다.

function handleSuccess () {
    const data = JSON.parse( this.responseText ); // convert data from JSON to a JavaScript object
    console.log( data );
}
function handleError () {
    // in the function, the `this` value is the XHR object
    console.log( 'An error occurred 😞' );
}

asyncRequestObject.onerror = handleError;

handleSuccess에서 그냥 html을 받지 않고, JSON을 JavaScript Object로 parse한 것을 콘솔에 출력하였는데, html은 parse하거나 사용하기가 어렵기 때문이다.




정리하면, XMLHttpRequest는 다음과 같이 쓴다.

function handleSuccess () { 
  console.log( this.responseText ); 
// the HTML of https://unsplash.com/}
function handleError () { 
  console.log( 'An error occurred \uD83D\uDE1E' );
}
const asyncRequestObject = new XMLHttpRequest();
asyncRequestObject.open('GET', 'https://unsplash.com');
asyncRequestObject.onload = handleSuccess;
asyncRequestObject.onerror = handleError;
asyncRequestObject.send();


GET - 데이터를 회수(retrieve)하는 것

POST - 데이터를 보내는(send) 것


보안 상의 이유로, 요청은 항상 데이터를 load하게 될 사이트와 동일한 도메인에 있는 데이터에 대해서만 가능하다. 예를 들어서, google.com으로부터 비동기적으로 요청을 보내기 위해서는 브라우저가 현재 google.com에 있어야만 한다. 이를 same-origin policy라고 한다.


이렇게 되어 있는 이유는, JavaScript가 페이지의 정보에 대한 통제권을 너무 많이 갖고 있기 때문이다. 모든 쿠키에 대해 접근할 수 있고, 유저가 입력한 키를 추적해 패스워드를 알아낼 수도 있다. 물론 정상적인 상황으로는 이렇게 되면 안될 것이다. 이 문제(same-origin policy)를 우회하는 방법이 CORS(Cross-Origin Resource Sharing)다. CORS는 서버에서 실행되는 기술이다. API를 제공하는 서비스들은 개발자들로 하여금 same-origin policy 문제를 해결하고 정보에 접근할 수 있도록 하기 위해서 CORS를 사용한다.










댓글