티스토리 뷰

1. AJAX와 비동기

 

1
2
3
4
5
6
7
8
9
10
 function ajax() {
   var oReq = new XMLHttpRequest();
    
  oReq.addEventListener("load"function() {
    console.log(this.responseText);
  });
    
   oReq.open("GET""http://www.example.org/example.txt");
   oReq.send();
}
cs

 

4라인의 익명함수는 8라인, 9라인보다 더 늦게 실행되는 함수입니다.

이 익명 함수는 비동기로 실행되며, 이벤트큐에 보관되다가 load이벤트가 발생하면(서버로부터 데이터를 브라우저가 받으면) 그때 call stack 에 실행되고 있는 함수가 없어서 비어있다면 stack에 올라와서 실행됩니다.

 

*동기/비동기

동기(Synchronous) - 이전의 작업이 다 끝날때 까지 기다렸다가 작업을 진행하는 방식. 버스를 예로 들어, 앞에 사람들이 다 탑승할때 까지 기다렸다가 탑승하는 것이다.

 

비동기(Asynchronous) - 이전 작업이  끝날때 까지 기다릴 필요 없이 다른 작업을 진행 할 수 있다. 비유하자면 집안일을 할 때 세탁할 옷을 세탁기에 돌리면서 요리를 한다거나 재료를 준비하는 행위 등과 같다.

 

*동기식

1
2
3
4
// synchronous
console.log('First Task');
console.log('Second Task');
console.log('Third Task');
cs

 

Output :

1
2
3
First Task
Second Task
Third Task

 

 

*비동기식

1
2
3
4
5
6
7
// asynchronous
console.log('First Task');
setTimeout(function(){
   console.log('Second Task');
}, 2000); 
 
console.log('Third Task');
cs

 

Output :

1
2
3
First Task
Third Task
Second
Task 

 

출 처 : http://www.phpmind.com/blog/2017/05/synchronous-and-asynchronous/

 

2. AJAX 응답처리

서버로부터 받아온 JSON 데이터문자열 형태이므로 브라우저에서 바로 실행할 수가 없습니다. 

따라서 문자열을 자바스크립트객체로 변환해야 데이터에 접근할 수가 있습니다.

이를 하려면 문자열 파싱을 일일이 해야 하는 불편함이 있습니다.

 

1
2
3
4
5
6
var oReq = new XMLHttpRequest();
oReq.addEventListener("load"function() {
    console.log(this.responseText);
});
oReq.open("GET""./json.txt"); //JSON 가져오기
oReq.send();
cs

 

객체 변환 형식 :

1
var json객체로변환된값 = JSON.parse("서버에서 받은 JSON 문자열");
cs

 

 

- AJAX 예제

 

*test.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
  <style>
    .outside{
      position: relative;
      background-color: blueviolet;
      width : 100px;
      font-size: 0.8em;
      color:#fff;
    }
  </style>
</head>
<body>
  <button>뭘까요?</button><br><br>
  <div class="outside">제가 좋아하는 과일은요...</div>
<script src="test.js"></script>
</body>
</html>
cs

 

*test.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
var btn = document.querySelector("button");
 
btn.addEventListener("click",function(){
  var oReq = new XMLHttpRequest();
 
  oReq.addEventListener("load",function(){
    console.log(this.responseText); //현재 String 타입이다.
    console.log(typeof this.responseText);
 
    var jsonobj=JSON.parse(this.responseText); // 문자열인 데이터를 parse()함수를 통해 JSON 객체로 바꿀 수 있다.
    console.log(jsonobj);
    console.log(typeof jsonobj);    //Object 타입
 
    console.log(jsonobj.favorites[1]); //이젠 데이터에 접근이 가능하다.
 
    fruit = jsonobj.favorites[1];
    var outside = document.querySelector(".outside");
    outside.innerHTML += "<span>"+fruit+"</span>";
  })
 
  oReq.open("GET""./json.txt");
  oReq.send();
});
cs

 

*json.txt

1
2
3
4
{
  "name" : "kwon",
  "favorites" : ["apple","orange"]
}
cs

 

참고 사이트 : http://www.edwith.org/



본 게시물은 개인적인 용도로 작성된 게시물입니다. 이후 포트폴리오로 사용될 정리 자료이니 불펌과 무단도용은 하지 말아주시고 개인 공부 목적으로만 이용해주시기 바랍니다.

' > 부스트코스' 카테고리의 다른 글

[WEB]HTML Templating  (2) 2018.07.29
[WEB]이벤트 버블링과 이벤트 위임(Event Bubbling and Event Delegation)  (0) 2018.07.29
[WEB]JavaScript 배열  (0) 2018.07.06
[WEB]Maven이란?  (0) 2018.06.29
[WEB]JSTL(JSP Standard Tag Library)  (0) 2018.06.29
댓글