JS 튜토리얼

제이에스 홈 JS 소개 JS 어디로 JS 출력 JS 문 JS 구문 JS 코멘트 JS 변수 제이에스렛 JS 상수 JS 연산자 JS 산술 JS 할당 JS 데이터 유형 JS 함수 JS 객체 JS 이벤트 JS 문자열 JS 문자열 메서드 JS 문자열 검색 JS 문자열 템플릿 JS 번호 JS 숫자 메서드 JS 배열 JS 배열 메서드 JS 배열 정렬 JS 배열 반복 JS 배열 상수 JS 날짜 JS 날짜 형식 JS 날짜 가져오기 메서드 JS 날짜 설정 방법 JS 수학 JS 랜덤 JS 부울 JS 비교 JS 조건 JS 스위치 JS 루프 In에 대한 JS 루프 의 JS 루프 JS 루프 동안 JS 브레이크 JS 이터러블 JS 세트 JS 맵 JS 유형 JS 유형 변환 JS 비트와이즈 JS 정규 표현식 JS 오류 JS 범위 JS 호이스팅 JS 엄격 모드 JS 이 키워드 JS 화살표 함수 JS 클래스 JS JSON JS 디버깅 JS 스타일 가이드 JS 모범 사례 JS 실수 JS 성능 JS 예약어

JS 버전

JS 버전 JS 2009(ES5) JS 2015(ES6) JS 2016 JS 2017 JS 2018 JS IE / 엣지 JS 연혁

JS 객체

객체 정의 개체 속성 개체 메서드 개체 표시 개체 접근자 객체 생성자 개체 프로토타입 객체 반복 가능 객체 세트 객체 맵 개체 참조

JS 함수

기능 정의 기능 매개변수 함수 호출 함수 호출 기능 적용 함수 클로저

JS 클래스

수업 소개 클래스 상속 클래스 정적

JS 비동기

JS 콜백 JS 비동기 JS 약속 JS 비동기/대기

JS HTML DOM

DOM 소개 DOM 메서드 DOM 문서 DOM 요소 DOM HTML DOM 양식 DOM CSS DOM 애니메이션 DOM 이벤트 DOM 이벤트 리스너 DOM 탐색 DOM 노드 DOM 컬렉션 DOM 노드 목록

JS 브라우저 BOM

JS 창 JS 화면 JS 위치 JS 연혁 JS 네비게이터 JS 팝업 경고 JS 타이밍 JS 쿠키

JS 웹 API

웹 API 소개 웹 양식 API 웹 기록 API 웹 스토리지 API 웹 작업자 API 웹 가져오기 API 웹 지리적 위치 API

JS 아약스

AJAX 소개 AJAX XMLHttp AJAX 요청 AJAX 응답 AJAX XML 파일 AJAX PHP AJAX ASP AJAX 데이터베이스 AJAX 애플리케이션 AJAX 예제

JS JSON

JSON 소개 JSON 구문 JSON 대 XML JSON 데이터 유형 JSON 구문 분석 JSON 문자열화 JSON 객체 JSON 배열 JSON 서버 JSON PHP JSON HTML JSON JSONP

JS 대 jQuery

jQuery 선택기 제이쿼리 HTML 제이쿼리 CSS 제이쿼리 DOM

JS 그래픽

JS 그래픽 JS 캔버스 JS 플로틀리 JS 차트.js JS 구글 차트 JS D3.js

JS 예제

JS 예제 JS HTML DOM JS HTML 입력 JS HTML 객체 JS HTML 이벤트 JS 브라우저 JS 편집기 JS 연습 JS 퀴즈 JS 인증서

JS 참조

자바스크립트 객체 HTML DOM 객체


AJAX - XMLHttpRequest 객체

AJAX의 핵심은 XMLHttpRequest 객체입니다.

  1. XMLHttpRequest 객체 생성
  2. 콜백 함수 정의
  3. XMLHttpRequest 객체 열기
  4. 서버에 요청 보내기

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 속성

속성 은 readyStateXMLHttpRequest의 상태를 유지합니다.

onreadystatechange속성은 readyState가 변경될 때 실행할 콜백 함수를 정의합니다.

status속성과 속성 statusTextXMLHttpRequest 개체의 상태를 유지합니다.

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가 변경될 때마다 호출됩니다.

readyState4이고 상태가 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) 트리거됩니다.