반응형

자바스크립트 개발 환경 Microsoft Visual Studio 2015 버전 HTML 기능 및 Chrome을 이용하고 있습니다.





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
<html>
<head>
    <meta charset="utf-8" />
    <style>
        .character {color : blue;}
        .word { color : deepskyblue;}
    </style>
    <script>
        var req = new XMLHttpRequest();
        req.onreadystatechange = function a() {
            console.log(this.readyState, this.status);
            if (this.readyState == 4) {
                console.log(this.response);
                var data = JSON.parse(this.response);
 
                for (var i in data) {
 
                    /*
                        t가 받아내는 값
                        <p id="template">
                            <span class="character">ID</span> : <span class="word">Msg</span> 
                        </p>
                    */
                    var t = document.getElementById("template").cloneNode(true);
                  
                    /*
                        id 삭제 이후
                        <p>
                            <span class="character">ID</span> : <span class="word">Msg</span> 
                        </p>
                        이때 t.children[0] = <span class="character">ID</span> 
                             t.children[1] = <span class="character">Msg</span> 
                             t.children[2] = undefined이다.
                    */
                    t.removeAttribute("id");
                    t.children[0].innerText = data[i].id;
                    t.children[1].innerText = data[i].msg;
 
                    // 차례대로 body에 하나씩 추가
                    document.body.appendChild(t);
                }
            }
        }
        req.open("GET""./input.txt");
        req.send();
 
 
    </script>
</head>
<body>    
    <p id="template">
        <span class="character">ID</span> : <span class="word">Msg</span> 
    </p>
    
</body>
</html>
 
//                                                       This source code Copyright belongs to Crocus
//                                                        If you want to see more? click here >>
Crocus



우선 로컬에서 이용하기 위해 chrome 속성에서 "대상 :" 부분의 경로 마지막에


"C:\~~\chrome.exe" --args --disable-web-security --user-data-dir=""


빨간색 부분을 추가하면 로컬에서 AJAX 실행이 가능하다.



위의 코드에서 readyState는 0일때 open 전, 1일때 open 후 ... 4일때 통신 완료를 의미하게 된다.


따라서 통신이 완료되었을 때(==4) 내가 통신해서 받아온 JSON 값을 data에 넣어주고


for문을 통해 data에 있는 값을 출력한다.



이때 JSON 파일은 아래같은 방식으로 이용한 예제이다.


[

{"id":"Crocus", "msg":"Hello AJAX"},

{"id":"Blog", "msg":"www.crocus.co.kr"},

{"id":"testonly", "msg":"this is test"}

]









반응형