본문 바로가기

웹/JSP

[JSP] <JavaScript> 비동기 기초

비동기처리란

  • JS + 비동기 처리 = 프론트엔드
  • 비동기처리는 데이터를 다룰 수 있는 기능이다.
    • 데이터는 DB에 존재 -> M파트 -> C에 접근 할 수 있는 기능
    • C파트 -> 서버 요청이 가능한 기능
    • 데이터를 다루다 보니 프레임워크가 필요해졌다.
      • Node Vue
      • React 
      • 등등
  • 비동기 처리를 하면 화면이동이 없다.
    • 하지만 FrontController를 사용하면 화면이동이 필수이다.
    • 비동기 처리만을 위한 Servlet이 별도로 필요하다.

 

jquery

  • 비동기처리를 구현하기 위해서는 jquery가 필요하다.
  • jquery 중에서 비동기 처리를 지원하는 메서드가 ajax이다.

https://releases.jquery.com/

 

jQuery CDN

jQuery CDN – Latest Stable Versions jQuery Core Showing the latest stable release in each major branch. See all versions of jQuery Core. jQuery 3.x jQuery 2.x jQuery 1.x jQuery Migrate jQuery UI Showing the latest stable release for the current and legac

releases.jquery.com

 

  • jsp파일에 라이브러리 주소 입력
<script src="https://code.jquery.com/jquery-3.7.1.min.js"
  integrity="sha256-/JqT3SQfawRcv/BIHPThkBvs0OEvtFFmqPF/lYI/Cxo="
  crossorigin="anonymous"></script>

비동기처리(페이지 로드)

데이터 파일 : json

  • JavaScript 객체 리터럴, 배열, 스칼라 데이터를 표현하는 텍스트 기반의 방식이다.
[ 
    {"name": "가렌", "content": 123}, 
    {"name": "작은 티모", "content": 6677}    
]

 

  • name, content는 key 값이다.
  • 가렌, 작은 티모, 123, 6677은 value 값이다.

데이터 요청 : ajax

<script type="text/javascript">
	$.ajax({
		type : "GET",
		url : "json/data.json",
		dataType : "json",
		success : function(data){
			var elem = "";
			
			$.each(data, function(index, data){
				elem += "<tr>";
				
				elem += "<td>"+(index+1)+"</td>";
				elem += "<td>"+data.name+"</td>";
				elem += "<td>"+data.content+"</td>";
				
				elem += "</tr>";
			});
			
			$("table tbody").append(elem);
		},
		error : function(){
			console.log("에러발생!");
		}
	});
</script>
  •  
  • type은 서버 요청방식을 지정한다.
    • GET
    • POST
  • url은 서버요청 url을 지정한다.
    • 서버 요청 
      • main.do
    • 파일요청
      • json/data1.josn
  • dataType은 전송 받아올 데이터의 타입 지정한다.
    • json
  • success는 성공했을 때의 행동을 지정한다.
    • function(){}
      • 인자 지정가능 : data
      • $.each = 반복문
  • error은 에러가 났을 때 행동을 지정한다.

데이터 표시 : html

<table border="1">
		<thead>
            <tr>
            	<th>화면에 보이는 번호</th>
                <th>이름</th>
                <th>내용</th>
            </tr>
        </thead>
        <tbody>
        </tbody>
</table>

비동기처리(버튼)

버튼 생성 : html

<img alt="더미 이미지 데이터 01" src="images/test01.jpg"> <br><br>
<img alt="더미 이미지 데이터 02" src="images/test02.jpg"> <br><br>
<button id="btn">버튼</button>

버튼 기능 지정 : ajax

$(document).ready(function(){
		$("#btn").on("click",function(){
		
			$.ajax({
				type : "POST",
				url : "apple.do",
				data : { 'banana' : '바나나' , 'kiwi' : 123 },
				dataType : 'text',
				success : function(data){
					console.log(data); // 사과 가 출력됨
		
					if(data=='사과'){
						$("body").append("<img alt='더미 이미지 데이터' 
                        			src='images/test03.jpg'>");
					}
					// "사과"라면 다시 입력하게하고,
					// "바나나"라면 통과!
				},
				error : function(error){
					console.log('에러발생!');
					console.log('에러의 종류 : '+error);
				}
			});
			
		});
	});
  • data에 {}로 감싼 값이 있다면 그건 서버로 보내는 값이란 뜻이다.

페이징 없이 요청을 받기 위한 Sevelt

@WebServlet("/apple.do")
public class TestServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
  
    public TestServlet() {
        super();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) 
    	throws ServletException, IOException {
		response.getWriter().append("Served at: ").append(request.getContextPath());
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) 
    	throws ServletException, IOException {
		System.out.println("JAVA 로그");
		
		System.out.println(request.getParameter("banana"));
		System.out.println(request.getParameter("kiwi"));
		
		response.setCharacterEncoding("UTF-8");
		PrintWriter out=response.getWriter();
		out.print("사과"); // != out.println("사과");
		
		// ID가 중복이라면? "사과"
		// 중복아니라면? "바나나"
	}

}

' > JSP' 카테고리의 다른 글

[JSP] <ajax> 비동기 아이디 중복 검사  (0) 2024.01.16
[JSP] <JSP> 세션 값 저장  (0) 2024.01.16
[JSP] <EL> 기초  (0) 2024.01.11
[JSP] <JavaScript> 페이지 주도권  (0) 2024.01.09
[JSP] <html> hidden 속성  (0) 2024.01.08