AJAX - XMLHttpRequest 객체
AJAX의 핵심은 XMLHttpRequest 객체입니다.
XMLHttpRequest 객체
모든 최신 브라우저는 XMLHttpRequest 객체를 지원합니다.
XMLHttpRequest 객체는 뒤에서 서버와 데이터를 교환하는 데 사용할 수 있습니다. 즉, 전체 페이지를 다시 로드하지 않고도 웹 페이지의 일부를 업데이트할 수 있습니다.
XMLHttpRequest 객체 생성
모든 최신 브라우저(Chrome, Firefox, Edge(및 IE7+), Safari, Opera)에는 내장 XMLHttpRequest 객체가 있습니다.
XMLHttpRequest 객체 생성 구문:
variable = new XMLHttpRequest();
예시
var xhttp = new XMLHttpRequest();
위의 예에서 사용된 "ajax_info.txt" 파일은 간단한 텍스트 파일이며 다음과 같습니다.
<h1>AJAX</h1>
<p>AJAX is not a programming language.</p>
<p>AJAX is a
technique for accessing web servers from a web page.</p>
<p>AJAX stands for
Asynchronous JavaScript And XML.</p>
도메인 간 액세스
보안상의 이유로 최신 브라우저는 도메인 간 액세스를 허용하지 않습니다.
즉, 웹 페이지와 웹 페이지에서 로드하려는 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 |
---|---|
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") |