본문 바로가기
JAVA

[JAVA] 다중 체크값 팝업창에서 AJAX로 저장방법

by GoodDayDeveloper 2022. 8. 15.
반응형

 

여러개의 값들을 AJAX를 통해 서버로 가져가는 방법을 정리해보겠습니다.

저는 체크값들을 팝업창에 뛰운 다음, 특정값을 추가하여 서버에 가져가는 것을 구현해보았습니다.

 

 

 

 

 

 

 

list.jsp

 

 

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
79
80
81
82
83
84
85
86
87
<script type="text/javascript" charset="utf-8">
 
function popupAnalDataUnit(){
        
    var uf = document.unitForm;
    var dataArr = new Array();
    
    if($("#metaTable input[name='metaChk']:checked").length == 0){
        alert("체크박스를 선택헤주세요.");
        return false
    }
    
    $("#metaTable input[name='metaChk']:checked").each(function(){
         dataArr.push($(this).val());
    });
    
    var metaarr = dataArr.join(",")
    $("#unitForm").find("input[name=arr]").val(metaarr);
    
    var url = "/gnb01/lnb01/list_popup.do?metaarr="+metaarr+"";
        window.open("" , "unitForm""width=1000, height=600, menubar=no, status=no, toolbar=no");
    uf.action = url;
    uf.target = "unitForm";
    uf.method = "post";
    uf.submit(); 
    
};
 
</script>
 
 
 
<form id="unitForm" name="unitForm" >
<input type="hidden" name="arr" value="" />
 
<div class="bbs_list">
    <table class="list_1" summary="" id="metaTable">
        <caption>List of posts</caption>
        <!-- // ENG1266 // 게시물 목록 -->
        <colgroup>
            <col />
            <col />
            <col />
            <col />
            <col />
            <col />
            <col />
            <col />
            <col />
        </colgroup>
        <thead>
            <tr>
                <th scope="col"><input type="checkbox" id="fontAllCheck" name="fontAllCheck" value="Y"/></th>
                <th scope="col">1</th>
                <th scope="col">2</th>
                <th scope="col">3</th>
                <th scope="col">4</th>
                <th scope="col">5</th>
                <th scope="col">6</th>
                <th scope="col">7</th>
                <th scope="col">8</th>                
            </tr>
        </thead>
        <tbody>
            <c:forEach var="result" items="${resultList}" varStatus="status">
                <tr>
                    <td class="nome frontMeta"><input type="checkbox" name="metaChk" value="${result.mt_idx }" /></td>
                    <td class="nome">1</td>
                    <td class="nome">2</td>
                    <td class="nome">3</td>
                    <td class="nome">4</td>
                    <td class="nome">5</td>
                    <td class="nome">6</td>
                    <td class="nome">7</td>
                    <td class="nome">8</td>
            </c:forEach>
        </tbody>
    </table>
</div>
 
 
 
<div>
    <a href="javascript:void(0);" onclick="popupAnalDataUnit();return false;" class="rbutton white small">POPUP</a>
</div>
</form>
 
cs

 

이곳에서는 특별한 것은 없이 체크값에 인덱스 값을 넣어준 다음,

onclick을 통해 함수를 실행시켜줍니다.

 

함수를 실행하게 되면 each 반복문을 통해서 체크박스에 체크된 값을 

dataArr라는 배열 변수에 넣어줍니다.

그리고 이 metaarr에 조인을 통해 쉼표를 넣어 구분시킨다음 url에 담아 서버로 보냅니다.

 

 

 

 

VO

 

1
2
3
4
5
public class CommonCodeVO{
 
    private List<Integer> arr = new ArrayList<Integer>();
 
}
cs

 

VO에 integer List 배열을 선언해줍니다.

 

 

 

 

 

Controller (popup)

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@RequestMapping(value = "/gnb01/lnb01/list_popup.do" , method = RequestMethod.POST)
public String list_chart(
        @ModelAttribute("searchVO") CommonCodeVO searchVO,
        HttpServletRequest request, @RequestParam(required = true, value = "metaarr"String mtIdx,
        ModelMap model) throws Exception {
 
    List<Integer> uniqueMtidxs = new ArrayList<Integer>(new HashSet<Integer>(searchVO.getArr()));  
    searchVO.setArr(uniqueMtidxs);
   
    List<CommonCodeVO> resultList = metaService.getMtListByArr(searchVO);
    model.addAttribute("resultList", resultList);
 
    
    return "tilespopup:bsite/gnb01/lnb01/popup";
}
cs

 

requestparam으로 받은 변수를 List<Integer>에서 선언언한 uniqueMtidxs에 넣어준 다음

VO에 넣어 조회한 후 리스트 배열값으로 가져옵니다.

 

 

 

XML (QUERYL)

 

1
2
3
4
5
6
7
8
<select id="getMtListByArr" parameterClass="CommonCodeVO"  resultClass="java.util.HashMap">
    SELECT 
        *
    FROM TBL
    <iterate prepend=" and mt_idx IN " property="arr" open="(" close=")" conjunction=",">
            #arr[]#
    </iterate>
</select>
cs

 

배열로 가져올때는 iterate를 사용하여 위와 같이 사용해주시면 됩니다.

 

 

 

 

반응형

 

 

 

popup.jsp 

 

 

 

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
<script type="text/javascript" charset="utf-8">
function popupAnalData(){
 
var subMainObj = new Object();
var submitArr = new Array();
$("#mtTable tbody tr").each(function() {
    var mt_idx = $(this).find("input[name='mt_idx']").val();
    var submitObj = new Object();
    submitObj["mt_idx"= mt_idx;
    submitObj["code_cate"]=codeCate;
    submitObj["mt_unit"= $("#tr_"+mt_idx).find(".unitList > option:selected").val();
    submitArr.push(submitObj);
});
 
subMainObj.arr = submitArr;
subMainObj.codeCate = codeCate;        
var jData = JSON.stringify(subMainObj);
 
$.ajax({
        url: path+"/gnb01/lnb02/create_ans.do",
        type: "POST"
        contentType: "application/json;charset=UTF-8",
        data:jData
    }).done(function(data) { 
        result = jQuery.parseJSON(data);                    
        if(result.res=="error"){
        alert("error");    
        }
        
        if(result.res=="ok"){
            close();
        }
    
    }).fail(function(e) {  
        alert("The attempt failed."+e);
    }).always(function() {  
    
    });  
 
}
</script>
 
 
 
<div>
<table class="list_1" cellspacing="0" id="mtTable" style="width:100%">
<colgroup>
    <col />
    <col />
</colgroup>
<thead>
    <tr>
        <th>1</th>
        <th>2</th>            
    </tr>
</thead>
<tbody>
<c:forEach var="result" items="${resultList}" varStatus="status">
<input type="hidden" name="mt_idx" id="mt_idx" value="${result.mt_idx }" />
    <tr id="tr_${result.mt_idx }">
    <input type="hidden" name="mt_idx" id="mt_idx" value="${result.mt_idx }" />
        <td class="title">${result.title }</td>
        <td class="unit">
        <select name="unitList" class="unitList" id="unitList${status.count }">
            <option value="">select</option>
            <option value="1">1</option>
            <option value="2">2</option>                   
        </select>
        </td>
    </tr>
</c:forEach>
</tbody>
</table>
</div>
<div> 
    <a href="javascript:void(0);" onclick="popupAnalData();return false;">Sumbit</a>
</div>
 
cs

 

이곳에서는 각각의 인덱스와 더불어 콤보박스의 값도 가져갈 예정입니다.

각각의 값을 선택한 다음 onclick을 통해 함수를 실행합니다.

 

스크립트에서는 each 반복문을 통해서 submitObj에 담은 다음 submitArr 배열 변수에 넣어준 다음,

JSON으로 변환 후 jData에 넣어주고 서버에 보냅니다.

 

 

 

 

 

 

 

Controller (서버 저장부분)

 

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
@SuppressWarnings("unchecked")
    @RequestMapping(value="/gnb01/lnb02/create_ans.do" ,method = RequestMethod.POST)
    @ResponseBody
    public String  insert_ans(
            @RequestBody String filterJSON,
            CommonCodeVO searchVO,
            ModelMap model,
            HttpServletResponse res
            ) throws Exception {
 
        JSONObject resMap = new JSONObject();
        res.setContentType("text/html; charset=UTF-8");
        PrintWriter out = res.getWriter();
    
        try{
 
            org.json.simple.parser.JSONParser jsonParser = new JSONParser();
            ObjectMapper mapper = new ObjectMapper();
            org.json.simple.JSONObject jsonObject = (org.json.simple.JSONObject) jsonParser.parse(filterJSON);
 
            String codeCate  = (String) jsonObject.get("codeCate");
            searchVO.setCode_cate(codeCate);    
            org.json.simple.JSONArray jarr= (org.json.simple.JSONArray) jsonObject.get("arr");
            List<CommonCodeVO> inArr =(List<CommonCodeVO>)mapper.readValue( jarr.toJSONString(),new TypeReference<List<CommonCodeVO>>(){ });
 
            gnb01lnb02service.insertCodeMeta(inArr,searchVO);
            resMap.put("res""ok");
            resMap.put("msg""Registered."); 
            
        }catch(Exception e){
            System.out.println(e.toString());
            resMap.put("res""error");
            resMap.put("msg""An error occurred during execution."); 
            if(!StringUtils.isNullOrEmpty(e.getMessage())) resMap.put("msg",e.getMessage());
        }
 
        out.print(resMap);
        return null;
    }
cs

 

 

 

jsonObject로 데이터를 가져온 다음 get을 통해 codeCate 값과  arr 배열 값을 꺼냅니다.

 

 

arr를 꺼낸 jarr의 json배열에서는 사진과 같이 각각의 데이터가 모두 들어가 있는 것을 알 수 있습니다.

 

 

 

 

그리고 VO 객체에 담아 리스트 객체를 만들어 줍니다.

 

 

 

 

 

 

 

insertCodeMeta Method
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
@Override
public void insertCodeMeta(List<CommonCodeVO> inArr, CommonCodeVO searchVO) {
        
    int prtCode = 0 ;
    try{
        CommonCodeVO cv = new CommonCodeVO();
        cv.setCode_cate(searchVO.getCode_cate());
        cv.setCode_use("N"); 
 
        prtCode = insertCodeMetaAction(cv);
    
        
    }catch(Exception e){
        String msg = "Registration failure.2"
        if(!StringUtils.isNullOrEmpty(e.getMessage())) msg=e.getMessage();
        throw new RuntimeException(msg);
    }    
    
    try{
        for(CommonCodeVO cv :inArr){
            cv.setMain_code(searchVO.getCode_cate()+"_"+searchVO.getCret_id()); 
            cv.setCode_name("new meta addition_"+prtCode);
            cv.setCode_depth(2);
 
            int res = insertCodeMetaAction(cv);
 
        }
    }catch(Exception e){
        String msg = "Registration failure.";
        if(!StringUtils.isNullOrEmpty(e.getMessage())) msg=e.getMessage();
        throw new RuntimeException(msg);
    }    
}
cs

VO객체에 대한 저장방식으로 저장하고,

List 객체를 만들어 줘서 List 객체만의 값을 저장하는 방식으로 구현해보았습니다.

 

 

반응형

댓글