TY blog

XMLHttpRequest / jQuery 데이터 요청, 응답 본문

프로그래밍 언어/JavaScript

XMLHttpRequest / jQuery 데이터 요청, 응답

주짓수하는 개발자 2023. 1. 10. 01:04

1. XMLHttpRequest 객체사용 

현재 대부분의 주요 웹 브라우저는 서버에 데이터를 요청하기 위한 XMLHttpRequest 객체를 내장하고 있습니다.

XMLHttpRequest 객체는 서버로부터 XML 데이터를 전송받아 처리하는 데 사용됩니다.

 

[로그인 소스 예문]

 	var xhr = new XMLHttpRequest();
	xhr.open("POST", "/loginOk.json", true); /* 1. 요청방식, 요청 URL, false : 동기 , true : 비동기  */
	
	xhr.setRequestHeader("Content-Type", 'application/x-www-form-urlencoded');
	xhr.send("id="+id+"&password="+pass); /* 2. 요청 URL 로 넘길 데이터 */
    	xhr.onreadystatechange = function (event) {
        if (xhr.readyState == 4) { /* 3. readyState */
            if (xhr.status == 200) { /* 4. status */
            	if(xhr.responseText == "noUser" || xhr.responseText == "fail"){ /* 5. responseText */
                	alert("아이디 또는 비밀번호가 일치하지 않습니다.");
                	document.getElementById("id").value = "";
                	document.getElementById("pass").value = "";
                	return false;
                }else {
                	location.href="/";
                }
            } else {
            	console.log("로그인 AJAX 통신실패");
            }
        }
    };

1-2. readyState 

이 값은 객체의 현재 상태( onreadystatechange 함수가 상태를 체크 )에 따라 다음과 같은 주기로 변화합니다.

readyState  
  0 - XMLHttpRequest.UNSET   XMLHttpRequest 객체가 생성된 상태 
  1 - XMLHttpRequest.OPENED   open() 메소드가 성공적으로 실행된 상태 
  2 - XMLHttpRequest.HEADERS_RECIEVED   send() 메소드를 실행 했지만 아직 데이터를 받지 못한 상태 
  3 - XMLHttpRequest.LOADING   데이터의 일부만을 받은 상태
  4 - XMLHttpRequest.DONE   모든 데이터를 받은 상태 

XMLHttpRequest.DONE 상태를 체크, status 속성이 200일때 ( 요청이 정상완료 ) 될 때 원하는 코드를 작성해 수행합니다.

 

1-3. responseText

요청후에 응답받을 데이터 

 

2. jQuery 

위에 소스코드를 jQuery ajax로 작성 

 

[로그인 jQuery 소스 예문]

/* Jquery 필요시 추가 */
// <script src="https://code.jquery.com/jquery-3.4.1.js"></script> 

$.ajax({
    url : "/loginOk.json",
    type : 'post',
    data : {
        id : id,
        password : pass,
    },
    success : function(data) {
        if(data == "noUser" || data == "fail"){
            alert("아이디 또는 비밀번호가 일치하지 않습니다.");
            document.getElementById("id").value = "";
            document.getElementById("pass").value = "";
            return false;
        } else {
            location.href="/";
        }
    },
    error : function() {
        console.log("로그인 AJAX 통신실패");
    }
});

jQuery 의  Ajax 호출은 async 값을 안 넣을 시  async : true 비동기 방식으로 동작합니다.

Comments