onnnzeoz
Published 2023. 4. 5. 19:32
제이쿼리를 활용한 Ajax Spring

Ajax

asynchronous java and xml

java와 비동기 방식의 xml을 활용해서 서버와 통신하는 방식

(최근에는 xml보다 json을 더 많이 사용한다)

일을 동시에 처리할 수 있는 비동기 방식이 가능한 이유 : 중간에 대리인이 있어서 할 수 있었음 ajax에서는 그게 XMLHttpRequest라는 객체임

(만약 얘를 안쓰면 받을 내용이 화면에 그대로 떠버렸음)

 

 

jQuery를 활용해서 Ajax를 사용하기

제이쿼리를 사용하면 코드가 간단해지며, 크로스브라우징 문제를 해결해줌

제이쿼리에서 제공하는 함수 : $.ajax([setting])

<body>
   <h3>ajax 로 html 내용 읽어오기</h3>
</body>
<div id="listArea"></div>
<button id="popup1">1번 팝업</button>
<button id="popup2">2번 팝업</button>
<button id="popup3">3번 팝업</button>
<div id="noticeArea"></div>

// ------------------------------------------------------

<script>
//ajax로 다른 html을 불러오기
//servlet-context.xml에 resources라는 요청을 보내야함
//보낼 데이터 없으므로 data:{}, 하거나 아예 안넣기

   $.ajax({
      type:'get', //http 요청방식, 기본값:get
      url:'resources/html/list.html', //여기로 요청이 전송됨
      data:{}, //요청시 포함되어질 데이터
      dataType:'html', //응답받을 데이터의 형식
      success:function(data){ //정상적으로 응답받으면 success콜백 호출
         //console.log(data);
         $('#listArea').html(data);
      },
      error:function(e){
         console.log(e);
      }
   });
   
   $('button').click(function(e){
      // 불러올 html 주소(스페이스)셀렉터, callback 함수가 들어간다.
      console.log(e.target.id);
      $('#noticeArea').load('resources/html/notice.html #'+e.target.id, 
    		  //#noticeArea 위치에 넣어줄건데 저기 넣을거는 notice.html파일인데
    		  //몇번째꺼인지는 #+e.target.id로
            function(res, stat){
         console.log(res)//전체 소스를 보여준다.
         console.log(stat)//불러오기 성공, 실패 여부를 보여준다.         
      });
   });
</script>

 

 

@ResponseBody //내가 반환하는 값을 자동으로 담아준다??? jason이 없으면 이게 정상적으로 동작하지 않음

 

 

profile

onnnzeoz

@onnnzeoz

비전공자의 개발 공부 일지입니다 💦 국비 풀스택 과정 수강중