IT story/JSP

[JSP 강의] L15JavaScript (L08sonAJAX.html)

jason719 2016. 12. 10. 21:55

L15 JAVA SCRIPT

L08JsonAJAX 
JSON 비동기식 통신

ex) L08sonAJAX.html
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
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
    <h3>JSON books.js or books를 화면에 출력시킨다.</h3>
    <button type="button" onclick="lodeDoc()">AJAX 통신</button>
    <div id="test">
        <table border="1">
            <tbody class="title">
                <tr>
                    <th>num</th>
                    <th>name</th>
                    <th>sort</th>
                    <th>price</th>
                    <th>author</th>
                    <th>info</th>
                </tr>
            </tbody>
            <tbody class="list">
            </tbody>
        </table>
    </div>
    <br />
    <script>
    function lodeDoc() {
        var http = new XMLHttpRequest(); //통신객체 생성 (HttpServlet과 동일)
        var url = "books.js";
        //get방식으로 url에 비동기식으로(true) 통신하겠다.
        //비동기식으로 통신할 때 실행할 함수 or 로직을 onreadystatechange에 구현해야한다.
        http.onreadystatechange = function() {
            if (this.readyState==4 && this.status==200) {
                //통신이 성공적이면 실행할 메소드
                console.log(this.responseText);
                //결과 값이 text이기 때문에 JSON.parse를 해줘야한다.
                var jsonParsing = JSON.parse(this.responseText);
                console.log(jsonParsing);
                bookList(jsonParsing);
            }
        }
        http.open("GET",url,true); //통신준비
        http.send();
    }
    function bookList(books) {
        var tableList = document.querySelector("#test table .list");
        var htmlList = "";
        for (var i = 0; i < books.length; i++) {
            htmlList +="<tr>";
            htmlList +="<td>"+books[i]["num"]+"</td>";
            htmlList +="<td>"+books[i]["name"]+"</td>";
            htmlList +="<td>"+books[i]["sort"]+"</td>";
            htmlList +="<td>"+books[i]["price"]+"</td>";
            htmlList +="<td>"+books[i]["author"]+"</td>";
            htmlList +="<td>"+books[i]["info"]+"</td>";
            htmlList +="</tr>";
        }
            tableList.innerHTML = htmlList;
    }
    </script>
</body>
</html>
cs


ex)books.js

1
2
3
4
5
6
7
8
[{    
"num" : "01_a123",
"name" : "모비딕",
"sort" : "소설",
"price" : 12000,
"author" : "민홍식",
"info" : "흰 고래 이야기"
}]
cs

출력내용

AJAX 통신 전

AJAX 통신 후