반응형

JQuery, Ajax로 JSON 데이터를 보내고, 가져오는 방법에 대해 알아보겠습니다.

 


 

1. HTML 폼

<form name="search" method="get" action="./">
    <ul>
    	<li>
            <select name="year" id="year">
                <option value="2021" selected>2021</option>
                <option value="2020">2020</option>
            </select>
        </li>
    	<li>
            <select name="term" id="term">
                <option value="">학기</option>
                <option value="1">1학기</option>
                <option value="2">2학기</option>
            </select>
        </li>
        <li>
            <select name="exhibition_id" id="exhibition_id">
                <option value="">교과목명</option>
            </select>
        </li>
    </ul>
</form>

- 연도와 학기, 교과목 select box를 만들었습니다.

 

- 연도를 선택하면 해당 연도의 데이터를 가져옵니다.

- 학기를 선택하면 선택된 연도 + 학기를 충족하는 데이터와 교과목명 option들을 가져옵니다.

 

 

2. JQuery, Ajax 전체 코드

$(document).ready(function(){

    if($("select[name=term]").val() == "") {
        $("select[name=exhibition_id]").attr("disabled",true);
    }

});

$(function() {

    $('#year').on('change', function () {
    
        $("select[name=term]").val("");        
        $(this).closest('form').submit();
        
    });

    $('#term').on('change', function () {
    
        term = $(this).val();
        
        if (term != "") {
            jQuery.ajax({
                type: "GET",
                url: "/registrations/_search.jsp",
                cache: false,
                data: {
                    category: '1',
                    year: '<%=year%>',
                    term: term
                },
                datatype: "JSON",
                success: function (obj) {
                    var data = JSON.parse(obj);

                    $.each(data, function (k, v) {
                        $('<option></option>').val(k).text(v).appendTo($('#exhibition_id'));
                    });

                },
                error: function (xhr, status, error) {
                    console.log("ERROR!!!");
                }
            });
            
        } else {
    
            $("select[name=exhibition_id]").attr("disabled",true);
        
        }

        $(this).closest('form').submit();
    });
    
});

- 전체 코드입니다.

- 먼저 학기의 값이 비어있다면 교과목을 선택할 수 없도록 disabled 시킨 상태입니다.

 

 

3. 연도 onchange 자세히 보기

 $('#year').on('change', function () {
 
     $("select[name=term]").val("");     
     $(this).closest('form').submit();
     
 });

- id가 year인 연도 셀렉트 박스 값이 바뀌면 코드가 실행됩니다.

 

- 먼저 name이 term인 학기 셀렉트 박스 값은 비어지도록 val("") 코드를 넣었습니다.

- 연도가 선택되면 가장 가까이 있는 form을 제출하도록 했습니다.

 

 

4. 학기 onchange 자세히 보기

$('#term').on('change', function () {

    $('#exhibition_id').html('<option value="">교과목명</option>');
    
    term = $(this).val();
    
    if (term != "") {
    
        $("select[name=exhibition_id]").attr("disabled",false);
    
        jQuery.ajax({
            type: "GET",
            url: "/registrations/_search.jsp",
            cache: false,
            data: {
                year: '<%=year%>',
                term: term
            },
            datatype: "JSON",
            success: function (obj) {
                var data = JSON.parse(obj);

                $.each(data, function (k, v) {
                    $('<option></option>').val(k).text(v).appendTo($('#exhibition_id'));
                });

            },
            error: function (xhr, status, error) {
                console.log("ERROR!!!");
            }
        });
        
    } else {
    
        $("select[name=exhibition_id]").attr("disabled",true);
        
    }

    $(this).closest('form').submit();
});

- id가 term인 학기 셀렉트 박스 값이 바뀌면 코드가 실행됩니다.

 

- 먼저 term의 값을 가져오고, 값이 비어있지 않다면 ajax 코드를 실행합니다.

- GET 방식으로 처리되고, /registrations/_search.jsp 파일로 값을 보냅니다.

 

- 보내는 데이터는 yearterm입니다.

- 데이터 타입은 JSON으로 되어있고, 데이터를 성공적으로 가져오면 교과목명 셀렉트 박스의 option들을 채웁니다.

- 데이터를 보내거나 가져오는 데에 실패하면 error 메시지를 뿌립니다.

 

- 위와 같은 작업이 끝난 후, 가장 가까이 있는 form을 제출합니다.

 

 

5. jsp 파일 (/registrations/_search.jsp)

<%@ page import="com.google.gson.Gson" %>

<%

    String year = request.getParameter("year")==null?"":request.getParameter("year");
    String term = request.getParameter("term")==null?"":request.getParameter("term");

    // 데이터 가져오는 코드 ...

    HashMap<String, String> exhibitions = new HashMap<String,String>();

    // HashMap에 데이터들 put ...

    Gson gson = new Gson();
    String jsonText = gson.toJson(exhibitions);
    out.print(jsonText);

%>

- year와 term 파라미터 값을 가지고 데이터를 가져옵니다.

- 가져온 데이터들은 HashMap에 넣습니다.

 

- 마지막으로 Gson 객체를 생성하고 json 데이터를 보냅니다.

 

 

 

이상으로 JQuery, Ajax로 JSON 데이터를 보내고 가져오는 방법에 대해 알아보았습니다.

 


 

반응형