ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 1129 jquery-study3-ajax / step25-serialize.html / AjaxTestServlet.java / step20-jquery-on.html / step26-data.html
    Spring 2022. 11. 29. 11:09

     

    //step25-serialize.html

    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
      <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/css/bootstrap.min.css">
      <script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.slim.min.js"></script>
      <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js"></script>
      <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <title>serialize</title>
    </head>
    <body>
    <div class="container pt-3">
    
    <form id="f1" action="front">
      이름 :<input type="text" id = "name" name="name">
       <input type="hidden" id = "command"
       name="command" value="register"> 
       <select name="tool" id = "tool">
       <option value="notepad">메모장</option>
       <option value="editplus">에디트플러스</option>
       <option value="eclipse">이클립스</option>
      </select> 
      <br>
      <input type="checkbox" name="menu" value="beer">맥주<br>
       <input type="checkbox" name="menu" value="pizza">피자<br> 
       <input type="button" value="test" id="test">
     </form>
     
     <!--
    		ajax 방식으로 전송시 
    		data:"name=장기하&tool=메모장&menu=맥주&menu=피자  와 같은 query string 을 만들어 
    		전송해야 한다 
    		위와 같은 form data 의 query string을 간편하게 만들수 있는 jquery의 serialize() 함수를 테스트해본다
    		data:$("#f1").serialize() 처럼 query string을 만들어 전송하면 됨 
     -->
    </div>
    </body>
    </html>

     

    //AjaxTestServlet.java

    package step4;
    
    import java.io.IOException;
    import java.io.PrintWriter;
    
    import javax.servlet.ServletException;
    import javax.servlet.annotation.WebServlet;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    @WebServlet("/AjaxTestServlet")
    public class AjaxTestServlet extends HttpServlet {
    	private static final long serialVersionUID = 1L;
    
    	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    		request.setCharacterEncoding("utf-8");
    		response.setContentType("text/html;charset=utf-8");
    		PrintWriter out = response.getWriter();
    		//ajax 응답은 필요한 데이터만 응답한다
    		out.print("등록 완료");
    		out.close();
    	}
    
    }

     

     

    * jquery로 memberName id를 셀렉트하여 '조규성'이 나오게 해본다

     

    //step25-serialize.html

    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
      <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/css/bootstrap.min.css">
      <script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.slim.min.js"></script>
      <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js"></script>
      <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <title>serialize</title>
    </head>
    <body>
    <div class="container pt-3">
    
    <form id="f1" action="front">
      이름 :<input type="text" name="name">
       <input type="hidden"
       name="command" value="register"> 
       <select name="tool">
       <option value="notepad">메모장</option>
       <option value="editplus">에디트플러스</option>
       <option value="eclipse">이클립스</option>
      </select> 
      <br>
      <input type="checkbox" name="menu" value="beer">맥주<br>
       <input type="checkbox" name="menu" value="pizza">피자<br> 
       <input type="button" value="test" id="test">
     </form>
     
     <!--
    		ajax 방식으로 전송시 
    		data:"name=장기하&tool=메모장&menu=맥주&menu=피자  와 같은 query string 을 만들어 
    		전송해야 한다 
    		위와 같은 form data 의 query string을 간편하게 만들수 있는 jquery의 serialize() 함수를 테스트해본다
    		data:$("#f1").serialize() 처럼 query string을 만들어 전송하면 됨 
     -->
     <script type="text/javascript">
     	$(document).ready(function() {
     		$("#test").click(function() {
     			//alert("ajax 요청시 서버로 전송할 데이터는 \n query string 형식으로 전송해야 함");
     			// form 의 query string을 생성해준다 
     			// alert($("#f1").serialize());
     			$.ajax({
     				type:"post",
     				url:"AjaxTestServlet",
     				data:"memberName =" + $("#memberName").val(),
     				success:function(result){
     					alert(result);
     				}
     			}); // ajax
     		}); // click
     	}); 	// ready
     </script>
    </div>
    </body>
    </html>

     

    memberName의 value가 조규성으로 넘어간 것을 확인할 수 있다

     

    //Servlet

    package step4;
    
    import java.io.IOException;
    import java.io.PrintWriter;
    
    import javax.servlet.ServletException;
    import javax.servlet.annotation.WebServlet;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    @WebServlet("/AjaxTestServlet") // 25의 url이 됨
    public class AjaxTestServlet extends HttpServlet {
    	private static final long serialVersionUID = 1L;
    
    	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    		request.setCharacterEncoding("utf-8");
    		response.setContentType("text/html;charset=utf-8");
    		PrintWriter out = response.getWriter();
    		String name = request.getParameter("memberName");
    		System.out.println("db insert name: " + name);
    		//ajax 응답은 필요한 데이터만 응답한다
    		out.print("등록 완료");
    		out.close();
    	}
    
    }

    입력한 데이터가 콘솔에서도 출력되는지 확인해본다

     

    //html

    serializable을 위해 둘의 이름을 동일하게 설정해준다

     

      // 아래는 ajax 방식으로 서버에 데이터를 전송할 때 폼 입력 양식 요소 별로
      // 각각 query string을 만들어서 전송하는 방식

     			$.ajax({
     				type:"post",
     				url:"AjaxTestServlet",
     				data:"memberName=" + $("#memberName").val() + "&command =" + $("#command").val(),
     				success:function(result){
     					alert(result);
     				}
     			}); // ajax

     

     

     serialize() 함수를 이용하는 방식

    이 입력양식을 전부 다 serialize 해 줄 것이고, 그 대상은 f1 이다

     

     

    //25

    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
      <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/css/bootstrap.min.css">
      <script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.slim.min.js"></script>
      <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js"></script>
      <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <title>serialize</title>
    </head>
    <body>
    <div class="container pt-3">
    
    <form id="f1" action="front">
      이름 :<input type="text" name="membername" id = "membername">
       <input type="hidden"
       name="command" value="register"> 
       <select name="tool">
       <option value="notepad">메모장</option>
       <option value="editplus">에디트플러스</option>
       <option value="eclipse">이클립스</option>
      </select> 
      <br>
      <input type="checkbox" name="menu" value="beer">맥주<br>
       <input type="checkbox" name="menu" value="pizza">피자<br> 
       <input type="button" value="test" id="test">
     </form>
     
     <!--
    		ajax 방식으로 전송시 
    		data:"name=장기하&tool=메모장&menu=맥주&menu=피자  와 같은 query string 을 만들어 
    		전송해야 한다 
    		위와 같은 form data 의 query string을 간편하게 만들수 있는 jquery의 serialize() 함수를 테스트해본다
    		data:$("#f1").serialize() 처럼 query string을 만들어 전송하면 됨 
     -->
     <script type="text/javascript">
     	$(document).ready(function() {
     		$("#test").click(function() {
     			//alert("ajax 요청시 서버로 전송할 데이터는 \n query string 형식으로 전송해야 함");
     			// form 의 query string을 생성해준다 
     			// alert($("#f1").serialize());
     			// 아래는 ajax 방식으로 서버에 데이터를 전송할 때 폼 입력 양식 요소 별로
     			// 각각 query string을 만들어서 전송하는 방식
     			/*
     			$.ajax({
     				type:"post",
     				url:"AjaxTestServlet",
     				data:"memberName=" + $("#memberName").val() + "&command =" + $("#command").val(),
     				success:function(result){
     					alert(result);
     				}
     			*/
     			// serialize() 함수를 이용하는 방식
     			 			$.ajax({
     				type:"post",
     				url:"AjaxTestServlet",
     				data:$("f1").serialize(),
     				success:function(result){
     					alert(result);
     				}
     			}); // ajax
     		}); // click
     	}); 	// ready
     </script>
    </div>
    </body>
    </html>

    serialize를 이용하여 더 간편하게 코드를 작성할 수 있다

     

     

    * step20-jquery-on.html

    이후 생성되는 이벤트에서 사용할 수 있는 코드를 배워본다

    <script type="text/javascript">
    	$(function(){ // document ready 시점 (document 객체가 준비되면 - 이미지 동영상은 제외)
    	// 위의 익명 함수가 한 번 실행된다. 이때, 현 페이지의 요소의 이벤트 처리를 등록
    	// id createBtn 이 클릭되면 동적으로 testDiv id 영역에 버튼을 생성한다
    		$("#createBtn").click(function(){
    			//alert($(this).html());
    			$("#testDiv").append("<button type='button' class = 'testBtn'>동적 버튼 </button>");
    		});
    	});
    </script>

    버튼 생성 버튼을 누르면 동적으로 버튼이 생성된다

    아이디는 유일해야 하니까 적절하지 않음. 
    동적으로 생성된 요소 (버튼)에 대해 이벤트 처리를 등록해본다

     

     

    - 작동하지 않는 코드
    (alert이 작동되지 않음)

    	$("testBin").click(function(){
    		alert("동적 버튼 클릭");
    		}); // click
    	});

     

    앞의 코드와 차이점
    현 페이지가 로드가 될 때에는 존재하지 않았던 요소들이다
    // 동적으로 생성된 요소 (버튼)에 대해 이벤트 처리를 등록해본다
    // 아래는 이벤트 처리에 대한 동작이 되지 않는다
    // 이유는 document 가 ready 되는 시점에 존재하지 않는 요소이기 때문에
    //    동적으로 생성된 요소에 대한 이벤트 처리는 jquery 의 on 으로 처리하면 된다

     

     

    - jquery on: 동적으로 생성되는 요소에 대한 이벤트 처리를 위한 함수
    $(셀렉터 - 동적 요소 (이벤트 처리 대상)를 가진 부모 요소).on("이벤트 타입", "셀렉터");


    testdiv 안에 버튼이 생성되니까 셀렉트를 testdiv 로 해준다

    	$("#testDiv").on("click", "testBtn", function(){
    		alert("동적 버튼 클릭");
    		});
    	}); //reday

    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
      <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/css/bootstrap.min.css">
      <script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.slim.min.js"></script>
      <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js"></script>
      <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <title>jquery-on</title>
    </head>
    <body>
    <div class="container pt-3">
    <!-- 아래 버튼을 누르면 testDiv 영역에 동적으로 버튼을 생성한다 -->
    <button type = "button" id="createBtn">버튼 생성</button>
    <hr>
    <div id="testDiv"></div>
    <script type="text/javascript">
    	$(function(){ // document ready 시점 (document 객체가 준비되면 - 이미지 동영상은 제외)
    	// 위의 익명 함수가 한 번 실행된다. 이때, 현 페이지의 요소의 이벤트 처리를 등록
    	// id createBtn 이 클릭되면 동적으로 testDiv id 영역에 버튼을 생성한다
    		$("#createBtn").click(function(){
    			//alert($(this).html());
    			$("#testDiv").append("<button type='button' class = 'testBtn'>동적 버튼 </button>");
    		});
    	// 동적으로 생성된 요소 (버튼)에 대해 이벤트 처리를 등록해본다
    	// 아래는 이벤트 처리에 대한 동작이 되지 않는다
    	// 이유는 document 가 ready 되는 시점에 존재하지 않는 요소이기 때문에
    	//		   동적으로 생성된 요소에 대한 이벤트 처리는 jquery 의 on 으로 처리하면 된다
    	/*
    	$("testBin").click(function(){
    		alert("동적 버튼 클릭");
    		}); // click
    		*/
    		// jquery on: 동적으로 생성되는 요소에 대한 이벤트 처리를 위한 함수
    		//				$(셀렉터 - 동적 요소 (이벤트 처리 대상)를 가진 부모 요소).on("이벤트 타입", "셀렉터", "익명함수");
    	$("#testDiv").on("click", "testBtn", function(){
    		alert("동적 버튼 클릭");
    		});
    	}); //reday
    </script>
    </div>
    </body>
    </html>

     

     

    // step26-data.html

     

    테이블의 특정 td 안에 특정한 정보를 심어두고 싶을 때
    1. hidden tag를 이용하는 방법 
    기존 방법 이외에 다른 방법을 배워본다

     

    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
      <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/css/bootstrap.min.css">
      <script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.slim.min.js"></script>
      <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js"></script>
      <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <title>jquery data 이용</title>
    
    </head>
    <body>
    <div class="container pt-3">
    <span id="member"  data-id="javaking" data-age="13">회원정보</span>
    <br><br>
    <button type="button" id="testBtn1">data 테스트1 data 속성 정보를 get 하는 버튼</button><br>
    <button type="button" id="testBtn2">data 테스트2</button><br>
    <button type="button" id="testBtn3">data 테스트3</button><br>
    <button type="button" id="testBtn4">data 테스트4</button><br><br>
    <span id="customer">고객정보</span>
    <script type="text/javascript">
    	$(function(){
    		$("#testBtn1").click(function(){
    			alert($("#member").data("id"));
    		});
    	});
    </script>
    </div>
    </body>
    </html>

    member로 찾아가서 data-id의 정보를 읽어서 alert으로 보여준다

     

    13이 나오도록 해본다

     

    set으로 정보 변경을 해본다
    data-id를 다른 걸로 바꿔서 특정하게 심어진 정보를 변경해본다

    <script type="text/javascript">
    	$(function(){
    		$("#testBtn1").click(function(){
    			alert($("#member").data("id"));
    			alert($("#member").data("age"));
    		});
    		$("#testBtn2").click(function(){
    			$("#member").data("id", "springking").data("age", 23);
    			alert("member id span 영역에 정보를 재할당");
    		});
    	});
    </script>

    테스트2를 누르고 다시 테스트 1을 눌러보면
    테스트 1의 alert으로 springking과 23 이 나온다

     

    customer id 영역에 data 정보를 set  / get 해본다

    	$("#testBtn3").click(function(){
    			$("#customer").data("id", "springmvc");
    			alert("customer id span 영역에 data 정보를 set");
    		});
    		$("#testBtn4").click(function(){
    			alert($("#customer").data("id"));
    		});
    	});

    3을 누르면 id에 springmvc가 set 된다

    4를 누르면 set 된 id를 get 해와서 spring mvc를 alert으로 띄워준다



    다수의 정보를 받아서 꺼내볼 때는 이와 같이 추가해주면 된다 get / set
    data 속성에 json 정보를 할당할 수도 있다

    	$("#testBtn3").click(function(){
    			// data 속성에 json 정보를 할당할 수도 있다
    			$("#customer").data("id", "springmvc").data("detailInfo", {age:19, nick:"손흥민"});
    			alert("customer id span 영역에 data 정보를 set");
    		});
    		$("#testBtn4").click(function(){
    			alert($("#customer").data("id"));
    			// data 속성에 저장된 json 정보를 받아와 출력해본다
    			let customer = $("#customer").data("detailInfo");
    			alert(customer.age + " " + customer.nick);
    		});



    객체나 마이바티스의 리스트를 제이슨에서 어레이로 받아서 응답받아서 사용하는 식으로 활용할 수 있다

    3 누르고 4 누르면 alert 으로 springking, 19 손흥민이 순차적으로 출력된다

     

    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
      <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/css/bootstrap.min.css">
      <script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.slim.min.js"></script>
      <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js"></script>
      <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <title>jquery data 이용</title>
    
    </head>
    <body>
    <div class="container pt-3">
    <span id="member"  data-id="javaking" data-age="13">회원정보</span>
    <br><br>
    <button type="button" id="testBtn1">data 테스트1 data 속성 정보를 get 하는 버튼</button><br>
    <button type="button" id="testBtn2">data 테스트2 data 속성정보를 set 하는 버튼</button><br>
    <button type="button" id="testBtn3">data 테스트3 customer id 영역에 data 정보를 set</button><br>
    <button type="button" id="testBtn4">data 테스트4 customer id 영역에 data 정보를 get</button><br><br>
    <span id="customer">고객정보</span>
    <script type="text/javascript">
    	$(function(){
    		$("#testBtn1").click(function(){
    			alert($("#member").data("id"));
    			alert($("#member").data("age"));
    		});
    		$("#testBtn2").click(function(){
    			$("#member").data("id", "springking").data("age", 23);
    			alert("member id span 영역에 정보를 재할당");
    		});
    		$("#testBtn3").click(function(){
    			// data 속성에 json 정보를 할당할 수도 있다
    			$("#customer").data("id", "springmvc").data("detailInfo", {age:19, nick:"손흥민"});
    			alert("customer id span 영역에 data 정보를 set");
    		});
    		$("#testBtn4").click(function(){
    			alert($("#customer").data("id"));
    			// data 속성에 저장된 json 정보를 받아와 출력해본다
    			let customer = $("#customer").data("detailInfo");
    			alert(customer.age + " " + customer.nick);
    		});
    	});
    </script>
    </div>
    </body>
    </html>

     

     

    'Spring' 카테고리의 다른 글

    Spring MVC  (0) 2022.11.29
    1129 spring17-mvc-basic  (0) 2022.11.29
    1128 jquery-study2 / step18-select-option.html  (0) 2022.11.28
    1128 spring16-MyBatis-MapperProxy-product  (0) 2022.11.28
    MyBatis + Spring  (0) 2022.11.25
Designed by Tistory.