• 회원가입
  • 로그인
  • 구글아이디로 로그인

[AJAX] JS - AJAX - Server Response (서버응답) - 콜백함수 사용 예제

 

XMLHttpRequest 객체 속성

 

readyState속성은 XMLHttpRequest 객체의 요청 접수 상태를 보유하고 있음.
이 onreadystatechange속성은 readyState가 변경될 때 실행할 함수를 정의함.

※ status속성과 statusText속성은 XMLHttpRequest 객체의 요청 처리 상태 보유

https://homzzang.com/b/js-80

 


 

onreadystatechange
readyState 속성 변경될 때 호출할 함수 정의.
readyState 상태가 변경 (1~4)될 때마다 호출됨. (즉, 4차례 촉발)

readyState
XMLHttpRequest 상태 표시 (= 요청 접수 상태)

0 : 요청이 초기화 안 된 상태.

1 : 서버 연결 설정된 상태

2 : 요청 접수된 상태

3 : 요청 처리 중 상태

4 : 요청 완료되고 응답 준비된 상태

 

responseText 

응답 데이터를 문자열로 반환.

 

responseXML 

응답 데이터를 XML 데이터로 반환.

 

status 

요청의 상태 번호 반환. (= 요청 처리 상태)

200 : "OK (통신성공 상태)"

403 : "Forbidden (접근금지 상태)"

404 : "Not Found (찾을 수 없음)"

더 자세한 정보는 아래 좌표 참고

https://www.w3schools.com/tags/ref_httpmessages.asp

 

statusText
상태 텍스트 (예 : "OK" 또는 "Not Found") 반환.

 


[응답 준비 상태]


readyState==4이고 status == 200 일 때, 응답 준비.
즉,

if (this.readyState == 4 && this.status == 200) {

 


[예제]

b.php 

<div id="demo">

<button type="button" onclick="hz()">아작스 배우기 좋은 사이트?</button>

</div>


<script>

function hz() {

  var xhttp = new XMLHttpRequest();

  xhttp.onreadystatechange = function() {

    if (this.readyState == 4 && this.status == 200) {

      document.getElementById("demo").innerHTML =

      this.responseText;

    }

  };

  xhttp.open("GET", "a.php", true);

  xhttp.send();

}

</script>

 

 

a.php 

<h1>홈짱닷컴 소개  Homzzang.com</h1>

<p>HTML - 기본틀</p>

<p>CSS - 디자인</p>

<p>JS - 동작기능</p>

<p>요청 방식 : <?php echo $_SERVER['REQUEST_METHOD']?> 방식</p>

<p>요청 시간 : <?php echo date("Y:m:d h:i:s", $_SERVER['REQUEST_TIME'])?></p>


 

 

콜백함수 사용 

 

1.
콜백함수는 다른 함수의 매개변수로 사용되는 함수를 의미.

 

2.

웹사이트에서 하나 이상의 AJAX 작업을 해야 하는 경우,
XMLHttpRequest 객체를 처리할 함수 하나와
각 AJAX 작업에 대한 하나의 콜백함수를 생성해야 함.

 

 

hz("url-1", aaa);

hz("url-2", bbb);


function hz(url, cFunction) {

  var xhttp;

  xhttp = new XMLHttpRequest();

  xhttp.onreadystatechange = function() {

    if (this.readyState == 4 && this.status == 200) {

      cFunction(this);

    }

  };

  xhttp.open("GET", url, true);

  xhttp.send();

}


function aaa(xhttp) {

  // 액션 코드

function bbb(xhttp) {

  // 액션 코드

}

 


b.php

<div id="demo">

<button type="button" onclick="hz('a.php', aaa)">아작스 배우기 좋은 사이트?

</button>

</div>


<script>

function hz(url, cFunction) {

  var xhttp;

  xhttp=new XMLHttpRequest();

  xhttp.onreadystatechange = function() {

    if (this.readyState == 4 && this.status == 200) {

      cFunction(this);

    }

  };

  xhttp.open("GET", url, true);

  xhttp.send();

}

function aaa(xhttp) {

  document.getElementById("demo").innerHTML = xhttp.responseText;

}

</script>

 


a.php

<h1>홈짱닷컴 소개  Homzzang.com</h1>

<p>HTML - 기본틀</p>

<p>CSS - 디자인</p>

<p>JS - 동작기능</p>

<p>요청 방식 : <?php echo $_SERVER['REQUEST_METHOD']?> 방식</p>

<p>요청 시간 : <?php echo date("Y:m:d h:i:s", $_SERVER['REQUEST_TIME'])?></p>


 

 

서버 응답 속성 

 

responseText 

응답 데이터를 문자열로 얻기

 

responseXML 

응답 데이터를 XML 데이터로 얻기

 

 

 

서버 응답 메서드

 

getResponseHeader () 
서버 자원의 특정 헤더 정보를 반환.

 

getAllResponseHeaders () 
서버 자원의 모든 헤더 정보를 반환.

 

 

 

responseText 속성

 

서버 응답을 JS 문자열로 반환

 


 

<div id="demo">

<button type="button" onclick="hz()">코딩 배우기 좋은 곳?</button>

</div>


<script>

function hz() {

  var xhttp = new XMLHttpRequest();

  xhttp.onreadystatechange = function() {

    if (this.readyState == 4 && this.status == 200) {

      document.getElementById("demo").innerHTML =

      this.responseText;

    }

  };

  xhttp.open("GET", "a.php", true);

  xhttp.send();

}

</script>



 

responseXML 속성

 

XMLHttpRequest 객체는 XML 파서를 내장
이 responseXML 속성은 서버 응답을 XML DOM 객체로 반환.

이 속성을 사용하면 응답을 XML DOM 객체로 파싱 가능.

 


b.php

<p id="demo"></p>

 

<script>

var xhttp, xmlDoc, txt, x, i;

xhttp = new XMLHttpRequest();

xhttp.onreadystatechange = function() {

  if (this.readyState == 4 && this.status == 200) {

    xmlDoc = this.responseXML;

    txt = "";

    x = xmlDoc.getElementsByTagName("DOMAIN");

    for (i = 0; i < x.length; i++) {

      txt = txt + x[i].childNodes[0].nodeValue + "<br>";

    }

    document.getElementById("demo").innerHTML = txt;

  }

};

xhttp.open("GET", "a.xml", true);

xhttp.send();

</script>

 


a.xml 

 

<GOODSITE>

    <SITE>

        <NAME>홈짱닷컴</NAME>

        <DOMAIN>Homzzang.com</DOMAIN>

    </SITE>

    <SITE>

        <NAME>그누보드</NAME>

        <DOMAIN>Sir.kr</DOMAIN>

    </SITE>

</GOODSITE>


 

 

getAllResponseHeaders () 메서드

 

서버 응답으로부터 모든 헤더 정보 반환

 


<p id="demo"></p>


<script>

var xhttp = new XMLHttpRequest();

xhttp.onreadystatechange = function() {

  if (this.readyState == 4 && this.status == 200) {

    document.getElementById("demo").innerHTML =

    this.getAllResponseHeaders();

  }

};

xhttp.open("GET", "a.php", true);

xhttp.send();

</script>

 


[결과값]

date: Wed, 17 Apr 2019 22:06:48 GMT server: Apache/2.4.34 (Win64) PHP/7.2.10 connection: Keep-Alive x-powered-by: PHP/7.2.10 content-length: 200 keep-alive: timeout=5, max=99 content-type: text/html; charset=UTF-8


 

 

getResponseHeader () 메서드 

 

특정 헤더정보 반환

 


 

<p>connection: <span id="demo"></span></p>


<script>

var xhttp=new XMLHttpRequest();

xhttp.onreadystatechange = function() {

  if (this.readyState == 4 && this.status == 200) {

    document.getElementById("demo").innerHTML =

    this.getResponseHeader("connection");

  }

};

xhttp.open("GET", "a.php", true);

xhttp.send();

</script>

 


[결과값]

connection: Keep-Alive



방문 감사합니다. (즐겨찾기 등록: Ctrl + D)

분류 제목
String JS - concat() 메서드 ★ - 문자열결합 (= 문자열합치기 = concat메서드 = 컨캣메서드)
String JS - endsWith() 메서드 - 지정문자열로 끝나는지(=종료) 여부 (IE12이상)
String JS - fromCharCode() 메서드 - 유니코드를 문자열로 변환
String JS - includes() 메서드 ★ - 지정문자열포함여부 (= includes메서드 = 인클루드즈메서드)
String JS - indexOf() 메서드(문자열) ★ - 처음일치문자열위치찾기 (= 문자열포함검사 = 인덱스어브메서…
String JS - lastIndexOf() 메서드(문자열) ★ - 마지막일치문자열위치찾기 (= 문자열포함검사 = 라스…
String JS - localeCompare() 메서드 - 문자열순서비교
String JS - match() 메서드 ★ - 일치하는 문자열 반환 (= match메서드 = 매치메서드) ※ 정규식 …
String JS - repeat() 메서드 - 지정횟수만큼 문자열반복 (= 리피트)
String JS - replace() 메서드(String용) ★ - 문자열 대체 (= replace메서드 = 리플레이스…
String JS - search() 메서드 - 문자열위치찾기 ※ 문자열포함검사
String JS - slice() 메서드 - 문자열 자르기 (= 문자열 일부 추출 = slice메서드 = 슬라이스 메서…
String JS - split() 메서드 - 문자열 쪼개기 (= split메서드 = 스플릿 메서드) ※ 이메일숨기기 (…
String JS - startsWith() 메서드 - 지정문자열로 시작 여부 (IE12이상)
String JS - substr() 메서드 ★ - 문자열 자르기 - 문자열의 특정 위치 이후의 특정 길이 만큼 반환
String JS - substring() 메서드 ★ - 문자열 일부 추출 (= 문자열 자르기 = substring메서드…
String JS - toLocaleLowerCase() 메서드 - 로캘 소문자로 변환
String JS - toLocaleUpperCase() 메서드 - 로캘 대문자로 변환
String JS - toLowerCase() 메서드 - 소문자로변환
String JS - toString() 메서드 (문자열경우) - 문자열타입으로 변경 (= toString메서드 = 투스…
6/67
목록
찾아주셔서 감사합니다. Since 2012