[Spring] REST 기초-2 : Ajax-get

 REST방식의 전송/수신 방식 중에는 Json 형식으로 데이터를 형성하여 JQuery, Ajax를 통해 전송하는 방식이 있다.

-데이터를 주고 받는 형식1(xml)

-데이터를 주고 받는 형식2(json)





 


※ Ajax의 경우 json 형식으로 가공하여 다루기가 편하다

-Ajax 기본 form
※ '$' 기호는 JQuery 사용을 위한 기호 이므로, 사전에 스크립트 태그의 추가가 필요, 해당 태그를 실행할 스크립트 태그 위쪽에 반드시 기입 할 것

<script src="http://code.jquery.com/jquery-3.5.1.min.js"></script>

① : 전송/수신 타입 지정(POST, GET, PUT, DELETE)

② : 요청하거나 받은 URL

③ : 사용할 데이터 타입(json)

④ : 전송/수신 성공 시 수행 할 동작이나 callback 함수 사용

- function(data)의 data는 수신 받은 데이터를 저장함

⑤ : 전송/수신 실패 시 수행 할 동작이나 callback 함수 사용(주로 오류 출력)


-사용 예시

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
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ page session="false"%>
<html>
<head>
<title>Home</title>
</head>
<body>
 
    <table class = "testAjax">
    </table>
 
</body>
<script src="http://code.jquery.com/jquery-3.5.1.min.js"></script> //JQuery 사용 시 필요
<script type="text/javascript" src="/resources/js/sampleTest.js"></script> //외부 자바 스크립트 호출
<script type="text/javascript">
$(document).ready(
function(){
    var div_ajax = $(".testAjax");
    var str = "";
    
    /*
        외부 스크립트의 함수 사용법
        스크립트 호출 후, 함수 사용을 위해 함수를 지정하여 저장한 변수 호출
        외부 스크립트 내부 예시
        ================================
        var testService = (function(){ 
            function 함수1(){. . .}
            function 함수2(){. . .}
        })
        =================================
        사용하는 경우 testService.함수1(. . .) 방식으로 
    */
 
    //getJSON을 이용한 호출
    testService.getlist(function(data){
        //값을 추출, body 태그 내부의 table 태그 내부에 삽입하여 출력
        $.each(data, function(index, item){
            str+="<tr>";
            str+="<td>"+item.bno+"</td>"+"<td>"+item.title+"</td>"+"<td>"+item.writer+"</td>"+"<td>"+item.regdateDate+"</td>"
            str+="</tr>"
        });
        div_ajax.html(str);
        
    });
    
    
    //ajax을 이용 : get 방식
    testService.getlistProto(function(data){
        $.each(data,function(index, item){
            console.log(item.bno);
        });
        
    });
    
    //스크립트에서 작성된 ajax
    $.ajax({
        url : '/board/replies/sampleGetTest.json',
        Type : "get",
        dataType : "json",
        success : function(data){
            console.log(data);
            $.each(data, function(index, item){
                console.log("bno : "+item.bno)
            })
        },
        error : function(){
            console.log("error");
        }
    });
 
    
    
})
 
</script>
 
</html>
 
cs


- 사용 자바 스크립트

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
 console.log("test Module....")
 var testService = (function(){
    //getJSON 방식 사용
    function getlist(callback, error){
        $.getJSON("/board/replies/sampleGetTest.json",
        function(data){
            if(callback){
                callback(data)
            }
        }).fail(function(){
            if(error){
                console.log("error");
            }
            
        });
 
    }
    //ajax:get 함수 방식
    function getlistProto(callback, error){
        $.ajax({
            type:'get',
            url : "/board/replies/sampleGetTest.json",
            contentType : "application/json; charset=utf-8",
            success : function(data){
                if(callback){
                    callback(data);
                }
            },
            error:function(error){
                console(error);
            }
        });
    }
 
     return {
         getlist:getlist,
         getlistProto:getlistProto
         };
 })();
cs

※ "/sampleGetTest" 는 단순히 값의 전체 호출을 하는 responsebody


※주의 사항

- 자바 스크립트 뒷 부분의 반환(return) 파트는 다음과 같이 설계 되어야 함

     return {
         getlist:getlist,
         getlistProto:getlistProto
         };

댓글