Front/js

Ajax) get방식/ post 방식 데이터를 받기

읽히는 블로그 2024. 7. 10. 12:36

▤ 목차

     

     

     

    ✔ 기본적인 세팅

    get 방식과 post 방식 모두, 서버에 요청을 하는 메서드이다.

    이때 get 방식은 url뒤에 붙여서 보낸다.

     

    ⌨ html 파일

    <script type="text/javascript">
    window.onload=()=>{
    	document.querySelector("#btnGet").onclick = getFunc;
    	document.querySelector("#btnPost").onclick = postFunc;
    }
    </script>
    </head>
    <body>
    <h2>Ajax get,post 요청</h2>
    <form name="frm">
    이름: <input type="text" name="name" value="tom"><br>
    나이: <input type="text" name="age"  value="23"><br>
    <input type="button" value="get" id="btnGet">
    <input type="button" value="post" id="btnPost">
    
    <div id="show"></div>
    
    </form>
    </body>

     

    이렇게 get 버튼을 누르면 get방식으로 post 버튼을 누르면 post 방식으로 데이터를 넘기도록 하겠다.

     

    💻 getpost.jsp

    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
        
    <% //html 파일에서 받아온다. fName 확인
    String irum = request.getParameter("name");
    String nai = request.getParameter("age");
    %>
    
    <%=irum + "님의 나이는 "+ nai+"살" %>

     

     

     


     

     

     

    ✔ get 방식

    ⌨ 코드

    let xhr;
    function getFunc(){
    	//alert('a');
    	let irum = frm.name.value;
    	let nai = frm.age.value;
    	//alert(irum+" " +nai);
    	
    	fName="getpost.jsp?name="+irum+"&age="+ nai; //html은 클라이언트 단에서 실행되는 것임. jsp는 서버단
    	xhr = new XMLHttpRequest();
    
    	xhr.open('get',fName,true);
    
    	xhr.onreadystatechange = function(){ 
    		if(xhr.readyState === 4){
    			if(xhr.status === 200){
    				getprocess();
    			}else{
    				alert("요청 실패:"+ xhr.status);
    			}
    		}
    	}
    	xhr.send(null);
    }
    function getprocess(){
    	let data = xhr.responseText;
    	let ss ="get 요청 결과" +data;
    	document.querySelector("#show").innerText=ss;
    }

     

    www.Ex.com?id=username&password=1234

    데이터는 key와 value 쌍으로 넣어야한다.

    2개 이상의 key-value 쌍 데이터를 보낼때는 & 마크로 구분해준다.

    url에 붙이므로, http 패킷의 해더에 포함되어 서버에 요청한다.

    body에 특별한 내욜을 넣을 것이 없기에 body가 빈상태로 보내진다.

    content-Type이라는 헤더필드는 들어가지 않는다.

    URL에 표현되므로 특정 페이지를 다른 사람에게 접속하게 할 수 있다.

    다만 데이터를 보내는 양의 한계가 있다.

     

     

     


     

     

     

    ✔ post 방식

    ⌨ 코드

    let xhr;
    function postFunc(){
    	//alert('a');
    	
    	let irum = frm.name.value;
    	let nai = frm.age.value;
    	//alert(irum+" " +nai);
    	
    	xhr = new XMLHttpRequest();
    	xhr.open('post',"getpost.jsp",true);
    
    	xhr.onreadystatechange = function(){ 
    		if(xhr.readyState === 4){
    			if(xhr.status === 200){
    				postprocess();
    			}else{
    				alert("요청 실패:"+ xhr.status);
    			}
    		}
    	}
    	xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
    	xhr.send("name="+irum+"&age="+ nai);
    }
    
    function postprocess(){
    	let data = xhr.responseText;
    	let ss ="post 요청 결과" +data;
    	document.querySelector("#show").innerText=ss;
    }

     

    데이버 전송을 기반으로 한 요청 메서드이다.

    GET 방식은 URL에 데이터를 붙여서 보내는 반면, post 방식은 URL에 붙여서 보내지 않고

    body에 데이터를 넣어서 보낸다.

    헤더 필드 중 데이터를 설명하는 Content-Type이라는 헤더필드(데이터 타입 명시)가 들어간다.

     


     

     

    😊정리

    post 방식이든 get 방식이는 클라이언트 측에서 볼 수 있다.

    바로 보이느냐, 아니느냐의 차이이다. 두방식 전부 보안을 생각한다면 암호화해야한다.

    GET방식의 요청은 캐싱(한번 접근 후, 요청할 시 빠르게 접근하기 위해 데이터를 저장해놓는다.)때문에 POST방식보다 빠르다.