AJAX - XMLHttpRequest 객체
AJAX의 핵심은 XMLHttpRequest 객체입니다.
- XMLHttpRequest 객체 생성
- 콜백 함수 정의
- XMLHttpRequest 객체 열기
- 서버에 요청 보내기
XMLHttpRequest 객체
모든 최신 브라우저는 XMLHttpRequest
개체를 지원합니다.
객체 는 XMLHttpRequest
배후에서 웹 서버와 데이터를 교환하는 데 사용할 수 있습니다. 즉, 전체 페이지를 다시 로드하지 않고도 웹 페이지의 일부를 업데이트할 수 있습니다.
XMLHttpRequest 객체 생성
XMLHttpRequest
모든 최신 브라우저(Chrome, Firefox, IE, Edge, Safari, Opera)에는 객체 가 내장되어 있습니다.
XMLHttpRequest
객체 생성 구문 :
variable = new XMLHttpRequest();
콜백 함수 정의
콜백 함수는 다른 함수에 매개변수로 전달되는 함수입니다.
이 경우 콜백 함수는 응답이 준비되었을 때 실행할 코드를 포함해야 합니다.
xhttp.onload = function() {
// What to do when the response is ready
}
요청 보내기
서버에 요청을 보내려면
XMLHttpRequest
객체의 open() 및 send() 메서드를 사용할 수 있습니다.
xhttp.open("GET", "ajax_info.txt");
xhttp.send();
예시
// Create an XMLHttpRequest object
const xhttp = new XMLHttpRequest();
// Define a callback function
xhttp.onload = function() {
// Here you can use the Data
}
// Send a request
xhttp.open("GET", "ajax_info.txt");
xhttp.send();
도메인 간 액세스
보안상의 이유로 최신 브라우저는 도메인 간 액세스를 허용하지 않습니다.
즉, 웹 페이지와 웹 페이지에서 로드하려는 XML 파일이 모두 동일한 서버에 있어야 합니다.
W3Schools의 예는 W3Schools 도메인에 있는 모든 열린 XML 파일입니다.
자신의 웹 페이지 중 하나에서 위의 예를 사용하려면 로드하는 XML 파일이 자체 서버에 있어야 합니다.
XMLHttpRequest 객체 메소드
Method | Description |
---|---|
new XMLHttpRequest() | Creates a new XMLHttpRequest object |
abort() | Cancels the current request |
getAllResponseHeaders() | Returns header information |
getResponseHeader() | Returns specific header information |
open(method, url, async, user, psw) | Specifies the request method: the request type GET or POST url: the file location async: true (asynchronous) or false (synchronous) user: optional user name psw: optional password |
send() | Sends the request to the server Used for GET requests |
send(string) | Sends the request to the server. Used for POST requests |
setRequestHeader() | Adds a label/value pair to the header to be sent |
XMLHttpRequest 객체 속성
Property | Description |
---|---|
onload | Defines a function to be called when the request is recieved (loaded) |
onreadystatechange | Defines a function to be called when the readyState property changes |
readyState | Holds the status of the XMLHttpRequest. 0: request not initialized 1: server connection established 2: request received 3: processing request 4: request finished and response is ready |
responseText | Returns the response data as a string |
responseXML | Returns the response data as XML data |
status | Returns the status-number of a request 200: "OK" 403: "Forbidden" 404: "Not Found" For a complete list go to the Http Messages Reference |
statusText | Returns the status-text (e.g. "OK" or "Not Found") |
onload 속성
객체를 사용 XMLHttpRequest
하여 요청이 응답을 수신할 때 실행할 콜백 함수를 정의할 수 있습니다.
함수는 객체 의 onload
속성에 정의되어 있습니다.XMLHttpRequest
예시
xhttp.onload = function() {
document.getElementById("demo").innerHTML = this.responseText;
}
xhttp.open("GET", "ajax_info.txt");
xhttp.send();
다중 콜백 함수
웹 사이트에 둘 이상의 AJAX 작업이 있는 경우 XMLHttpRequest
개체를 실행하기 위한 하나의 함수와 각 AJAX 작업에 대해 하나의 콜백 함수를 만들어야 합니다.
함수 호출에는 URL과 응답이 준비되었을 때 호출할 함수가 포함되어야 합니다.
예시
loadDoc("url-1", myFunction1);
loadDoc("url-2", myFunction2);
function loadDoc(url, cFunction) {
const xhttp = new XMLHttpRequest();
xhttp.onload = function() {cFunction(this);}
xhttp.open("GET", url);
xhttp.send();
}
function myFunction1(xhttp) {
// action goes here
}
function myFunction2(xhttp) {
// action goes here
}
onreadystatechange 속성
속성 은 readyState
XMLHttpRequest의 상태를 유지합니다.
이 onreadystatechange
속성은 readyState가 변경될 때 실행할 콜백 함수를 정의합니다.
status
속성과 속성 은 statusText
XMLHttpRequest 개체의 상태를 유지합니다.
Property | Description |
---|---|
onreadystatechange | Defines a function to be called when the readyState property changes |
readyState | Holds the status of the XMLHttpRequest. 0: request not initialized 1: server connection established 2: request received 3: processing request 4: request finished and response is ready |
status | 200: "OK" 403: "Forbidden" 404: "Page not found" For a complete list go to the Http Messages Reference |
statusText | Returns the status-text (e.g. "OK" or "Not Found") |
이 onreadystatechange
함수는 readyState가 변경될 때마다 호출됩니다.
가 readyState
4이고 상태가 200이면 응답이 준비된 것입니다.
예시
function loadDoc() {
const xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML =
this.responseText;
}
};
xhttp.open("GET", "ajax_info.txt");
xhttp.send();
}
이벤트는 readyState 의 onreadystatechange
각 변경에 대해 한 번, 네 번(1-4) 트리거됩니다.