본문 바로가기
✨ Front-end/jQuery

[jQuery] Ajax에서 serialize()로 form 데이터 모두 넘기기

by 환풍 2023. 9. 13.
728x90

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core_rt" %>    
<!DOCTYPE html>
<html lang="en">
<head>
  <title>Bootstrap Example</title>
  <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.2/dist/css/bootstrap.min.css">
  <script src="https://cdn.jsdelivr.net/npm/jquery@3.6.4/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.2/dist/js/bootstrap.bundle.min.js"></script>
  <script src="https://code.jquery.com/jquery-3.6.0.js"></script>
  <script type="text/javascript">
   function insertCard(){
       if($("#name").val().length==0||$("#company").val().length==0||
          $("#tel").val().length==0){
          alert('DataCheck!');
           $("#name").val('');
           $("#company").val('');
           $("#tel").val('');
           $("#name").focus();    
           return false;
       }
       $.ajax({
           url:'${pageContext.request.contextPath}/card/insertCard',
           //data:{company:$("#company").val(),tel:$("#tel").val()},
           data:$("form#cardForm").serialize(),
           dataType:"text",
           type:"POST",
           success:function(obj){
               insertCallProcess(obj);
           },
           error:function(){
               alert('error');
           }
       });
   }//function 
   function insertCallProcess(obj){
          if(obj=='success'){
              alert('Card등록을 성공했습니다');
              goListView();
          }   
   }
   function goListView(){
       document.location.href='${pageContext.request.contextPath}/card/listCard';
   }
    $(function(){
        $("button#send").click(function(){
            insertCard();
        });
    });
  </script> 
</head>
<body>
 
<div class="container">
  <h2>Card form Injection</h2>
  <form action="#" id="cardForm">
    <div class="form-group">
      <label for="email">Name:</label>
      <input type="text" class="form-control" id="name" placeholder="Enter name" name="name">
    </div>
    <div class="form-group">
      <label for="company">Compny:</label>
      <input type="text" class="form-control" id="company" placeholder="Enter company" name="company">
    </div>
    <div class="form-group">
      <label for="tel">Tel:</label>
      <input type="text" class="form-control" id="tel" placeholder="Enter text" name="tel">
    </div>   
    <button type="button" id="send" class="btn btn-primary">Send</button>
  </form>
</div>
 
</body>
</html>
cs

JSP

위 jsp의 form 태그안에 있는 데이터들을 ajax에서 한번에 넘겨줄 것이다.

js

원래대로라면 주석과 같이 컨트롤러로 데이터를 넘길때, 하나하나 지정해주어야하지만,

serialize()를 사용하면 데이터들이 name에 준 이름으로 한번에 넘어간다.

Send 버튼을 누르면 데이터들이 알아서 직렬화되서 이름에 맞게 넘길 수 있다.

DTO와 컨트롤러

CardFormBean 객체를 생성해서 컨트롤러에서 바로 찍어봐도 매개변수가 같으면 값이 찍히는걸 확인할 수 있다.

반응형

댓글