본문 바로가기

Ajax & jQuery

Ajax (1) - 데이터 전송받기 (javascript,jQuery,Ajax)

오늘 진행 할 예제 

test1.jsp => javascript로만 Ajax를 구현
test2.jsp => JQuery의 Ajax 기능을 통해서 Ajax를 구현 (많이씀)
test3.jsp => JQuery로만 Ajax를 구현
test4.jsp => JQuery의 Ajax를 이용하여 get,post방식으로 데이터 넘기기
test5.jsp => jQuery의 Ajax를 이용하여 JSON 형식으로 데이터 주고받기

 

 

1. JavaScript를 이용해 Ajax를 구현하는 예제

JavaScript를 이용하여 서버로 보내는 HTTP request를 만들기 위해서는 그에 맞는 기능을 제공하는 Object의 인스턴스가 필요

XMLHttpRequest 객체 생성
xmlReq = new XMLHttpRequest(); // nonIE (Microsoft사의 Browser가 아닌 경우 - 크롬, 사파리..)
xmlReq = new ActiveXObject("Msxml2.XMLHTTP"); // IE 5.0 이상 버전
xmlReq = new ActiveXObject("Microsoft.XMLHTTP"); // IE 5.0 이전 버전

 

 

Ajax를 활용하기위해서는 서버와 요청/응답을 주고받아야 하기 때문에 매번 XMLHttpRequest 객체 생성해야함 => 모듈화하는 javascript문 생성

 

 

ajaxUtil.js - WebContent/data/js/

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
//XMLHttpRequest: ajax의 비동기 통신 객체 (브라우저에 내장돼있음) 필요
//모듈화
 
var xmlHttp;
 
function createXMLHttpRequest(){
    //특징: 브라우저에 영향을 많이 받음 (호환이 되는것도 안되는것도 있음)
 
    var xmlReq = false;
 
    if(window.XMLHttpRequest) {
 
        xmlReq = new XMLHttpRequest();  // Non-Microsoft Browser 
    } else if (window.ActiveXObject) {
        try{
 
            xmlReq = new ActiveXObject("Msxml2.XMLHTTP"); //Microsoft Browser 5.0 이상이면
 
        }catch (e) {
 
            xmlReq = new ActiveXObject("Microsoft.XMLHTTP"); //Microsoft Browser 5.0 이전버전
        }
    }
 
    return xmlReq;
}
cs

 

 

 

 

test1.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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
<%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%
    request.setCharacterEncoding("UTF-8"); 
    String cp = request.getContextPath(); 
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script type="text/javascript" src="<%=cp%>/data/js/ajaxUtil.js"></script>
 
<script type="text/javascript">
 
    function sendIt() {
 
        //XMLHttpRequest 객체를 생성
        xmlHttp = createXMLHttpRequest();
        // 1.브라우저 검색 2. 그에 맞게 xmlReq 객체 생성 후 여기에 반환
 
        var query = "";
        var su1 = document.getElementById("su1").value;
        var su2 = document.getElementById("su2").value;
        var oper = document.getElementById("oper").value;
 
        // get방식 데이터 전송
        query = "test1_ok.jsp?su1="+su1+"&su2="+
                su2 + "&oper="+oper; 
 
 
        xmlHttp.onreadystatechange = callback;
        // onreadystatechange라는 프로퍼티(메소드)는
        // 서버가 작업을 마치고 클라이언트한테 
        // 정보나 데이터를 되돌려 줄 때 자동으로 실행되는 메소드
        // 콜백메소드(자동으로 실행되는 함수)명은 사용자 정의
 
        //서버한테 보내기
        xmlHttp.open("GET",query,true);
        //위에 함수가 get방식이므로
        //true: 비동기방식으로 보낸다 (서버에 a작업던져놓고,  나는 딴 짓하고 있다. 대신 받아주는 함수 필요 => callback)
        //ajax방식은 대부분 true
        xmlHttp.send(null);
        // POST 방식으로 보낼때는 uri에 줄줄이 데이터를 못붙이므로
        // null자리에다가 써주면 됨
 
        //서버에서 처리작업 맡긴거임.
 
    }
 
    function callback(){
 
        if(xmlHttp.readyState==4) { // ppt 참고 
 
            if(xmlHttp.status==200) {
 
                printData();
 
            }
 
        }
 
    }
 
    function printData() {
 
        //받아낸 XML(responseXML)에 root라는 애가 있음
        var result = 
            xmlHttp.responseXML.getElementsByTagName("root")[0];
        //Tag오면 Element's'
        //Id오면 Element
 
        var out = document.getElementById("resultDIV");
 
 
        out.innerHTML = "";
        out.style.display = "";
        // 초기화 작업
        // 처음 실행 시 : resultDIV에 10이 들어가고
        // 두번 째 실행 시 : 20이 들어가려면 그 전의 10이 지워져 있어야 함
 
        var data = result.firstChild.nodeValue; // root의 첫번째 value값
 
        out.innerHTML = data; // html 형식으로 데이터를 out에다가 뿌려라
 
    }
 
 
</script>
 
 
</head>
<body>
 
<input type="text" id="su1">
 
<select id="oper">
    <option value="hap">더하기</option>
    <option value="sub">빼기</option>
    <option value="mul">곱하기</option>
    <option value="div">나누기</option>
</select>
 
<input type="text" id="su2">
 
<input type="button" value=" = " onclick="sendIt();"/><br/>
 
<!-- <div id="resultDIV" style="display: none;"></div> -->
<!-- 결과를 = 아래 하얀부분에 띄움.  id는 사용자 정의 -->
 
<!-- 이렇게 테이블 형태 안에 결과값을 출력할 수도 있음 -->
<table border="1" width="600">
<tr height="30">
<td></td>
<td></td>
</tr>
<tr height="30">
<td></td>
<td><div id="resultDIV" style="display: none;"></div></td>
</tr>
</table>
 
</body>
</html>
cs

 

 

 

 

test1_ok.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
<%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%
    request.setCharacterEncoding("UTF-8"); 
    String cp = request.getContextPath(); 
 
    // 서버 역할
    int su1 = Integer.parseInt(request.getParameter("su1"));
    int su2 = Integer.parseInt(request.getParameter("su2"));
    String oper = request.getParameter("oper");
 
    int sum = 0;
 
    if(oper.equals("hap")) 
        sum = su1 + su2;
    else if(oper.equals("sub"))
        sum = su1 - su2;
    else if(oper.equals("mul"))
        sum = su1 * su2;
    else if(oper.equals("div"))
        sum = su1 / su2;
 
    // 아래부분은 xml 말고도 text 로도 내보내줄 수 있음 (완벽한모양도 가능 -> 코드가 길어질것임)
 
    // 나온 결과를 클라이언트한테 돌려줄 차례
    // 모양을 갖춰서 돌려줘야함
    StringBuffer sb = new StringBuffer(); // StringBuffer를 꼭 이용해야하는건 아님
 
    // 돌려주는 데이터를 xml 형태로 돌려줌
    sb.append("<?xml version='1.0' encoding='utf-8'?>\n");
    sb.append("<root>" + sum + "</root>"); // root는 xml 이 들어있음
 
    //되돌려준다
    response.setContentType("text/xml;charset=utf-8");
    response.getWriter().write(sb.toString());
    // 클라이언트의 콜백함수로 돌아감
 
    // 여기서 xml형태로 짜줬으니깐, 아래 html코드는 필요 없음
    // 표형태로 서버쪽에서 미리 짜서 반환해줄 수도 있음 디자인은 자유롭게 구성 가능
 
%>
cs

 

 

 

*★ 2. JQuery에 있는 Ajax 기능을 통해서 Ajax를 구현하는 예제 *

test2.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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
<%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%
    request.setCharacterEncoding("UTF-8"); 
    String cp = request.getContextPath(); 
%>
 
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
 
<script type="text/javascript" src="<%=cp%>/data/js/jquery-3.4.1.min.js"></script>
 
<script type="text/javascript">
 
    $(function(){
 
        $("#sendButton").click(function() {
 
            var params = "subject=" + $("#subject").val() + 
                "&content=" + $("#content").val(); //쿼리임 데이터만 넘길 것!
 
            $.ajax({
                type:"POST",                //전송방식
                url:"test2_ok.jsp",    //주소
                data:params,            //전송데이터
                dataType:"xml"// 받을 때 데이터 타입
                success:function(args){ // 이 xml 형태의 데이터를 args로 받음 (바깥으로부터 들어옴)
                                                            // xml 형태니깐 parsing 작업을 해서 받아야함
                    $(args).find("status").each(function(){    //status 해당 태그 검색. eaxh는 반복문
 
                        alert($(this).text()); // this의 text 형태로 출력해라 
 
                    });
 
                    var str = "";
                    $(args).find("record").each(function(){    // each : 반복문 => record를 다 찾아내라
 
                        var id = $(this).attr("id"); // attribute 넣어라
                        var subject = $(this).find("subject").text();
                        var content = $(this).find("content").text();
 
                        str += "id=" + id +
                            ", subject=" + subject +
                            ", content=" + content + "<br/>";
                    });
 
                    // 반복문으로 만들어낸 데이터를 html로 바꿔서 str을 출력해라
                    $("#resultDiv").html(str); 
                    // javascript 방식에서 out.innerHTML = data; 이거랑 같은 코딩
 
 
                },
 
                beforeSend:showRequest,
                // 보내기 전에!  showRequest가서 검사 (showRequest는 사용자정의)
                //beforeSend는 true값을 받아야만, 위 ajax부분을 통해 서버로 데이터를 보냄
                error:function(e){
                    // 에러가 나면 e: 에러메서지가 여기 들어와 있을것임    
                    alert(e.responseText); // error msg는 String이기 때문에 responseText
                    //xml을 받을때는 e.responseXml
                }
            });
        });
    });
 
    function showRequest(){ 
 
        var flag = true//무조건 일단 true
 
        if(!$("#subject").val()) { //jQuery에서 가져오는 값이 없으면,
 
            alert("제목을 입력하세요!");
            $("#subject").focus();
            return false;
 
        }
 
        if(!$("#content").val()) { 
 
            alert("내용을 입력하세요!");
            $("#content").focus();
            return false;
 
        }
 
        // subject, content 둘 다 값이 넣어져 있으면
        return flag;
 
    }
 
</script>
 
 
 
</head>
<body>
 
제목:<input type="text" id="subject"/><br/>
내용:<input type="text" id="content"/><br/>
<input type="button" id="sendButton" value="보내기"/>
<br/>
<br/>
<!-- 출력할 위치 지정 -->
<div id="resultDiv"></div>
 
</body>
</html>
cs

 

 

 

 

test2_ok.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
<%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%
    request.setCharacterEncoding("UTF-8"); 
    String cp = request.getContextPath(); 
 
    String subject = request.getParameter("subject");
    String content = request.getParameter("content");
 
%>
 
<root>
    <status>권장도서</status> 
 
    <record id="1">
        <subject><%=subject %></subject> <!-- 사용자가 넘긴 데이터들 출력 -->
        <content><%=content %></content>
    </record>
 
    <!-- 추가 데이터 -->
    <record id="2">
        <subject>피구왕 통키</subject> 
        <content>스포츠</content>
    </record>
 
</root>
cs

 

 

3. 오로지 JQuery로만 Ajax를 구현하는 예제

test3.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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
<%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%
    request.setCharacterEncoding("UTF-8"); 
    String cp = request.getContextPath(); 
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSON형식으로 데이터 주고 받기</title>
<script type="text/javascript" src="<%=cp%>/data/js/jquery-3.4.1.min.js"></script>
 
<script type="text/javascript">
 
     // test1.jsp =>  javascript로만 Ajax를 구현 
    // test2.jsp => JQuery에 있는 Ajax 기능을 통해서 Ajax를 구현 (많이씀)
    // test3.jsp => JQuery로만 Ajax를 구현
 
    // 이 예제는 test2.jsp에서의 방식을 압축한 느낌임
    $(function() {
 
        $("#saveButton").click(function() {
 
            var value1 = $("#userId").val();
            var value2 = $("#userPwd").val();
 
             //1. Get방식으로 데이터를 넘기는 법 
            $.get("test3_ok.jsp",{userId:value1,userPwd:value2},//userId=value1
 
                // get방식으로 보낸 데이터 (test3_ok.jsp) 결과값 처리된걸 
                //args에서 받음 
                function(args){
 
                // 결과값 받아서 복잡한 작업을 추가해야하면 이 사이에서 해주면 됨
 
                // 그러고서, 결과 출력
                $("#resultDIV").html(args); 
            }); 
 
     //GET방식과 POST방식 둘다 기재할 수 없으므로 주석처리 
/*             // 2.Post방식
            $.get("test3_ok.jsp",{userId:value1,userPwd:value2},
                    function(args){
                    $("#resultDIV").html(args); 
                });
        }); */
 
 
            $("#clearButton").click(function() {
                $("#resultDIV").empty();
            });
    });
    });
 
 
 
});
 
 
 
</script>
 
</head>
<body>
 
    아이디:
    <input type="text" id="userId" />
    <br /> 패스워드:
    <input type="text" id="userPwd" />
    <br />
 
    <button id="sendButton">전송</button>
 
    <br/>
    <br/>
    <div id="resultDIV"></div>
 
 
</body>
</html>
<%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%
    request.setCharacterEncoding("UTF-8");
    String cp = request.getContextPath();
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script type="text/javascript" src="<%=cp%>/data/js/jquery-3.4.1.min.js"></script>
 
<script type="text/javascript">
 
// test4.jsp : jQuery에 있는 ajax의 기능 이용하여 get,post방식으로 데이터 넘기기
 
$(document).ready(function(){
 
    $("#saveButton").click(function(){
 
        var params = "userId=" +$("#userId").val() +
                    "&userPwd=" +$("#userPwd").val();
 
        $.ajax({
 
            type:"POST",
            url:"test4_ok.jsp",
            data:params,
            success:function(args){
                $("#resultDIV").html(args);
            },
            beforeSend:showRequest,
 
            error:function(e){
 
                alert(e.responseText);//텍스트로 받음
 
            }
 
        });
 
    });
 
    //클리어 시키는 작업
    $("#clearButton").click(function(){
        $("#resultDIV").empty();
    });
 
    //데이터넣는지 확인하는 함수
    function showRequest() {
 
        //무조건 트루
        var flag = true;
 
        if(!$("#userId").val()){
 
            alert("아이디을 입력하세요!");
            $("#userId").focus();
            return false;
        }
 
        if(!$("#userPwd").val()){
 
            alert("패스워드을 입력하세요!");
            $("#userPwd").focus();
            return false;
        }
 
        return flag;
 
    }
 
 
});
 
 
</script>
 
</head>
<body>
    아이디:
    <input type="text" id="userId" />
    <br/> 패스워드:
    <input type="text" id="userPwd" />
    <br/>
 
    <button id="saveButton">전송</button>
    <button id="clearButton">지우기</button>
 
    <br/>
    <br/>
    <div id="resultDIV"></div>
 
</body>
</html>
<%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%
    request.setCharacterEncoding("UTF-8"); 
    String cp = request.getContextPath(); 
 
    String userId = request.getParameter("userId");
    String userPwd = request.getParameter("userPwd");
 
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
 
아이디:<%=userId %><br/>
패스워드:<%=userPwd %><br/>
 
<!-- 이건 xml이 아니라 text. => 여기선 text로 돌려주는걸 기억 -->
 
</body>
</html>
cs

 

 

 

 

아이디:

 


패스워드:

 



 

 

 

test3_ok.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
<%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%
    request.setCharacterEncoding("UTF-8"); 
    String cp = request.getContextPath(); 
 
    String userId = request.getParameter("userId");
    String userPwd = request.getParameter("userPwd");
 
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
 
아이디:<%=userId %><br/>
패스워드:<%=userPwd %><br/>
 
<!-- 이건 xml이 아니라 text. => 여기선 text로 돌려주는걸 기억 -->
 
</body>
</html>
cs

 

 

 

test4_ok.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
88
89
90
91
92
93
94
95
96
<%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%
    request.setCharacterEncoding("UTF-8");
    String cp = request.getContextPath();
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script type="text/javascript" src="<%=cp%>/data/js/jquery-3.4.1.min.js"></script>
 
<script type="text/javascript">
 
// test4.jsp : jQuery에 있는 ajax의 기능 이용하여 get,post방식으로 데이터 넘기기
 
$(document).ready(function(){
 
    $("#saveButton").click(function(){
 
        var params = "userId=" +$("#userId").val() +
                    "&userPwd=" +$("#userPwd").val();
 
        $.ajax({
 
            type:"POST",
            url:"test4_ok.jsp",
            data:params,
            success:function(args){
                $("#resultDIV").html(args);
            },
            beforeSend:showRequest,
 
            error:function(e){
 
                alert(e.responseText);//텍스트로 받음
 
            }
 
        });
 
    });
 
    //클리어 시키는 작업
    $("#clearButton").click(function(){
        $("#resultDIV").empty();
    });
 
    //데이터넣는지 확인하는 함수
    function showRequest() {
 
        //무조건 트루
        var flag = true;
 
        if(!$("#userId").val()){
 
            alert("아이디을 입력하세요!");
            $("#userId").focus();
            return false;
        }
 
        if(!$("#userPwd").val()){
 
            alert("패스워드을 입력하세요!");
            $("#userPwd").focus();
            return false;
        }
 
        return flag;
 
    }
 
 
});
 
 
</script>
 
</head>
<body>
    아이디:
    <input type="text" id="userId" />
    <br/> 패스워드:
    <input type="text" id="userPwd" />
    <br/>
 
    <button id="saveButton">전송</button>
    <button id="clearButton">지우기</button>
 
    <br/>
    <br/>
    <div id="resultDIV"></div>
 
</body>
</html>
cs

 

 

 

 

5. jQuery의 Ajax를 이용하여 JSON 형식으로 데이터 주고받기

JSON은 map방식으로 <Key,Value> 형태로 데이터가 저장됨

 

 

test5.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
<%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%
    request.setCharacterEncoding("UTF-8"); 
    String cp = request.getContextPath(); 
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSON형식으로 데이터 주고 받기</title>
<script type="text/javascript" src="<%=cp%>/data/js/jquery-3.4.1.min.js"></script>
 
<script type="text/javascript">
 
$(function(){
 
    $("#sendButton").click(function(){
 
        var params = "userId=" + $("#userId").val() +
            "&userPwd=" + $("#userPwd").val();
 
        $.ajax({
 
            type:"POST",
            url:"test5_ok.jsp",
            data:params,
            dataType:"json"//받는 type은 json방식
            success:function(args) { // 결과값이 json방식으로 args로 들어온 상태
                var str = "";
 
                // 결과값 가공
                // 여기선 간단하게 str에 쭉 뿌리지만 나중엔 표로 만들어도 됨
                // 그 디자인을 test5_ok.jsp 에서 가공한 다음 통째로 여기로 보내도 됨 
                // => 그 경우는 여기서 그 결과를 html로 뿌려주기만 하면 됨
 
                for(var i=0; i<args.length; i++) {
 
                    str += "id=" + args[i].id;
                    str += ",userId=" + args[i].userId;
                    str += ",userPwd=" + args[i].userPwd + "<br/>";
 
                }
 
                $("#resultDIV").html(str); 
 
            },
 
            error:function(e) {
 
                alert(e.responseText);
            }
 
 
        });
 
    });
 
});
 
 
 
</script>
 
</head>
<body>
 
    아이디:
    <input type="text" id="userId" />
    <br /> 패스워드:
    <input type="text" id="userPwd" />
    <br />
 
    <button id="sendButton">전송</button>
 
    <br/>
    <br/>
    <div id="resultDIV"></div>
 
 
</body>
</html>
cs

 

아이디:


패스워드:

 



 

 

test5_ok.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
<%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%    
    // 일단 이번 시간엔 JSON 전체적인 구조만 훑고 그 다음 세세하게 들어갈 거임
    request.setCharacterEncoding("UTF-8"); 
    String cp = request.getContextPath(); 
    
    String userId = request.getParameter("userId");
    String userPwd = request.getParameter("userPwd");
    
    String result = "";
    
    // userId를 3번 출력
    for (int i=1; i<=3; i++) {
        
        result += "{\"id\":\"" + i;;
        result += "\",\"userId\":\"" + userId;
        result += "\",\"userPwd\":\"" + userPwd + "\"},";
        
        // JSON(키 : 값) - 따옴표로 반드시 묶여있어야 한다
        // {"id":"1","userId":"suzi","userPwd":"123"},
        // {"id":"1","userId":"suzi","userPwd":"123"},
        // {"id":"1","userId":"suzi","userPwd":"123"},
    }
    
    // 마지막 쉼표는 빼준다
    result = result.substring(0,result.length()-1);
    result = "[" + result + "]";
    
        // 대괄호로 묶는게 JSON 방식
        // [
        // {"id":"1","userId":"suzi","userPwd":"123"}, 
        // {"id":"1","userId":"suzi","userPwd":"123"},
        // {"id":"1","userId":"suzi","userPwd":"123"}
        // ]
                
        // db 에는 일반 텍스트형태의 데이터를 꺼내서 
        // json형태([])로 반드시 만들어줘야함 => 이 값을 ajax한테 보냄
    
    out.print(result);
        // 클라이언트쪽으로 넘어가서 json방식으로 바꾸는게 아니라 데이터 자체를 json 방식으로 보내야함
 
    
    
%>
cs