Asynchronous Javascript And XML

브라우저가 가지고있는 XMLHttpRequest 객체를 이용해서 전체 페이지를 새로 고치지 않고도 페이지의 일부만을 위한 데이터를 로드하는 기법

즉, JavaScript를 사용한 비동기 통신, 클라이언트와 서버간에 XML 데이터를 주고받는 기술

 

<body>
<button onclick="loadJsp()">Request data</button>
<script>
    function loadJsp() {
        let xhttp = new XMLHttpRequest();
        xhttp.open('get', 'test01.jsp', true);
        xhttp.send();

        xhttp.onreadystatechange = function () {
            if (this.readyState == 4 && this.status == 200) {	// this = xhttp
                alert(this.responseText);
                document.querySelector('#demo').innerHTML = this.responseText;	// responseText에 서버로부터 불러온 자료가 들어있음
            }
        }
    }
</script>
</body>

 

● xhttp.open(method, url, async) : 경로 설정

- method : "get" or "post" 방식

- url : 보내려는 url

- async : 비동기여부 [생략가능, d:true]

 

● xhttp.send() : 서버로 요청전송

 - post방식일때는 파라미터에 값을 넣어서 전송함

 

xhttp.onreadystatechange : 서버로 보낸 요청에 대한 응답을 받았을 때 동작

 - 여기서 서버로부터 받은 자료를 담은 responseText를 처리해야함

 

○ xhttp.readyState

  • 0 (uninitialized) - request가 초기화되지 않음
  • 1 (loading) - 서버와의 연결이 성사됨
  • 2 (loaded) - 서버가 request를 받음
  • 3 (interactive) - request(요청)을 처리하는 중
  • 4 (complete) - request에 대한 처리가 끝났으며 응답할 준비가 완료됨

○ xhttp.status

  • 200 - OK!
  • 403 - Forbidden
  • 404 - not found
  • 500 - Internal Server Error
더보기

HTTP 상태 코드

100 - 정보 응답

200 - 성공 응답

300 - 리다이렉트 메시지

400 - 클라이언트 에러

500 - 서버 에러

 

 

JQuery

● .ajax()

$.ajax({
  url: '주소',
  type: 'GET' or 'POST',
  data: {
    id: 'europa'
  },
  dataType: 'json, xml, script, text, html 등',
  success: function(data) {
    # 성공시 실행될 콜백함수구현
  },
  error: function(data) {
    # 실패시 실행될 콜백함수구현
  }
});

- url : 요청 URL

- type : method설정

- data : 서버로 보낼 데이터

- dataType : 서버에서 데이터 처리후 반환할 데이터타입

- success : 성공시 실행할 콜백함수

 

 

● .get() 약식메서드

$.get('url', 'data', function(res) {
    // success 콜백함수
  });

 

● .post() 약식메서드

$.post('url', 'data', function(res) {
    // success 콜백함수
  });

 

'Langauge > Javascript' 카테고리의 다른 글

Form 관련 속성, 함수  (0) 2020.08.05
[JQuery] 기본  (0) 2020.07.27
for in 반복문  (0) 2020.07.22
BOM(Browser Object Model)  (0) 2020.07.22
ECMAScript5 (ES5) - Array 메서드  (0) 2020.07.22

+ Recent posts