221121 Visual Studio Code(이철희쌤 3일차 2)

Gukbbap·2022년 11월 21일
0

보강

목록 보기
4/7

원래 ajax(Asynchronouse JAvascript XML)가 첨 나왔을 때 아무도 믿지 않음
2004년경 구글이 gmap,gmail 등으로 증명하면서 웹개발의 필수 기술이 되어버림
SPA(Single Page Application)

외울거.. 페이지를 이동하지 않기 위해서는..

var xhr = new XMLHttpRequest(); // 심부름꾼 생성(정확히는 통신객체 생성)
xhr.open("메소드", "URL", true ; // 심부름꾼에게 할일 지정
//메소드 : 어떤 방법으로 갔다 올건지 (post, get, delete)
// URL : 위치 주소
// 비동기여부 : 동기방식인지 비동기 방식인지 확인 통상 무조건 true를 작성한다. 
       //false를 사용할 경우 요청이 도달할 때까지 아무런 작동을 하지 않기 떄문에 
       //ajax의 의의에 유배 된다 그렇기 때문에 true를 기본값으로 준다. 
       //혹여 요청이 도달 할때까지 대기 해야 한다면 false를 사용한다.

xhr.send(); //시킨대로 하라고 엔터 치는것


---
### 실습

>```js
   var xhr = new XMLHttpRequest(); // 심부름꾼 생성(통신해줄 아저씨)
   xhr.open("get","data.html",true); // 심부름꾼에게 할일 지정
   //심부름꾼의 상태변화 모니터링
   xhr.onreadystatechange = function(){
    // 우린 중간과정은 관심없고, 통신이 끝나고 오는 결과에만 관심이 있음
      if(xhr.readyState == 4  && xhr.status == 200){
            console.log(xhr.responseText)   // 심부름꾼이 서버에서 받아온 값
      }
   }
   xhr.send();   // 시킨대로 하시옹

xhr.open에 있는 data.html을 console.log에서 responseText로 받아오기 때문에

console에 사진처럼 출력 된다.

이를 console뿐만 아니라 display에서도 출력하려면

<body>
    <div id="disp"></div>
</body>
<script>
//원래 ajax(Asynchronouse JAvascript XML)가 첨 나왔을 때 아무도 믿지 않음
// 2004년경 구글이 gmap,gmail 등으로 증명하면서 웹개발의 필수 기술이 되어버림
// SPA(Single Page Application)

var vdisp = document.querySelector("#disp");
// 요부분은 일단 한번 외웁니당!
var xhr = new XMLHttpRequest(); // 심부름꾼 생성(통신해줄 아저씨)
xhr.open("get","data.html",true); // 심부름꾼에게 할일 지정
//심부름꾼의 상태변화 모니터링
xhr.onreadystatechange = function(){
// 우린 중간과정은 관심없고, 통신이 끝나고 오는 결과에만 관심이 있음
if(xhr.readyState == 4 && xhr.status == 200){
console.log(xhr.responseText) // 심부름꾼이 서버에서 받아온 값
vdisp.innerHTML = xhr.responseText;
}
}
xhr.send(); // 시킨대로 하시옹

```

와 같이 body 안에 출력시키면 된다.


심부름꾼 아저씨

var xhr = new XMLHttpRequest(); // 심부름꾼 생성(통신해줄 아저씨)

전역 변수로 사용하지 않는다.
다른 function에서 xhr을 불러오면 작업하다 다른 곳으로 팔려 가기 때문에 값이 제대로 출력되지 않기 때문이다.
그렇기 때 XMLHttpRequest는 지역변수로 생성해서 사용하여야 한다.

//심부름꾼 아저씨는 전역변수로 쓰지 않아용/ 
   //필요할 때 지역변수로 생성해서 사용합니당
   var xhr = new XMLHttpRequest(); // 심부름꾼 생성(통신해줄 아저씨)

아무리 코딩을 잘 해봤자 개념이 없으면 기회가 오지 않는다.

일반화 하지 않은 기본 방식

<!DOCTYPE html>
<meta charset="UTF-8">
<body>
    <div id="disp"></div>
    <input type="button" value="누르숑" onclick="f_ajax()">
</body>
<script>
var vdisp = document.querySelector("#disp");
function f_ajax(){
    var xhr = new XMLHttpRequest(); // 항상 지역변수로 쓸 것!
   xhr.open("get","data.html",false); 
   xhr.onreadystatechange = function(){
      if(xhr.readyState == 4  && xhr.status == 200){
            alert(xhr.responseText) 
            vdisp.innerHTML = xhr.responseText;
        }
   }
   xhr.send();
}
</script>


#### 방식 1
>```html

<!DOCTYPE html>
<meta charset="UTF-8">
<body>
    <div id="disp"></div>
    <input type="button" value="누르숑" onclick="f_ajax()">
</body>
<script>
var vdisp = document.querySelector("#disp");
function f_ajax(p_method,p_url,p_cb){
    var xhr = new XMLHttpRequest(); // 항상 지역변수로 쓸 것!
   xhr.open(p_method,p_url,false); 
   xhr.onreadystatechange = function(){
      if(xhr.readyState == 4  && xhr.status == 200){
            alert(xhr.responseText)
            p_cb(xhr.responseText); 
            //vdisp.innerHTML += xhr.responseText;
        }
   }
   xhr.send();
}
</script>

방식 2

<!DOCTYPE html>
<meta charset="UTF-8">
<body>
    <div id="disp"></div>
    <input type="button" value="누르숑" onclick="f_ajax()">
</body>
<script>
var vdisp = document.querySelector("#disp");
function f_ajax(p_setting){   
  				// ↑ 매개변수를 flexible하게 사용하기 위해 json사용
    var xhr = new XMLHttpRequest(); // 항상 지역변수로 쓸 것!
   xhr.open(p_setting.method,p_setting.url,false); 
   xhr.onreadystatechange = function(){
      if(xhr.readyState == 4  && xhr.status == 200){
            alert(xhr.responseText)
            p_setting.p_cb(xhr.responseText); 
            //vdisp.innerHTML += xhr.responseText;
        }
   }
   xhr.send();
}
</script>

방식 3

<!DOCTYPE html>
<meta charset="UTF-8">
<body>
    <div id="disp"></div>
    <input type="button" value="누르숑" onclick="f_ajax()">
</body>
<script>
var vdisp = document.querySelector("#disp");
function f_ajax(p_setting){   // 매개변수를 flexible하게 사용하기 위해 json사용
    var xhr = new XMLHttpRequest(); // 항상 지역변수로 쓸 것!
   xhr.open(p_setting.method,p_setting.url,false); 
   xhr.onreadystatechange = function(){
      if(xhr.readyState == 4  && xhr.status == 200){
            alert(xhr.responseText)
            p_setting.p_cb(xhr.responseText); 
            //vdisp.innerHTML += xhr.responseText;
        }
   }
   xhr.send();
}
f_ajax({
    method:"get",
    url:"data.json",
    p_cb:function(rslt){
        console.log("화긴:",rslt);
    }
})
</script>

문자열 출력

<!DOCTYPE html>
<meta charset="UTF-8">
<body>
    <div id="disp"></div>
    <input type="button" value="누르숑" onclick="f_ajax()">
</body>
<script>
var vdisp = document.querySelector("#disp");
function f_ajax(p_setting){   // 매개변수를 flexible하게 사용하기 위해 json사용
    var xhr = new XMLHttpRequest(); // 항상 지역변수로 쓸 것!
   xhr.open(p_setting.method,p_setting.url,false); 
   xhr.onreadystatechange = function(){
      if(xhr.readyState == 4  && xhr.status == 200){
          if(p_setting.dataType == "json"){
            p_setting.success(JSON.parse(xhr.responseText)); 
          }else {
            p_setting.success(xhr.responseText); 
          }
        }
   }
   xhr.send();
}
f_ajax({
    method:"get",
    url:"data.json",
    dataType:"text",
    // 오해가 있는데 이번에 잘 이해하길, 이미받은 데이터를 JSON.parse 할거냥?
    success:function(rslt){
        console.log("화긴:",rslt);
    }
})
</script>

json 출력

<!DOCTYPE html>
<meta charset="UTF-8">
<body>
    <div id="disp"></div>
    <input type="button" value="누르숑" onclick="f_ajax()">
</body>
<script>
var vdisp = document.querySelector("#disp");
function f_ajax(p_setting){   // 매개변수를 flexible하게 사용하기 위해 json사용
    var xhr = new XMLHttpRequest(); // 항상 지역변수로 쓸 것!
   xhr.open(p_setting.method,p_setting.url,false); 
   xhr.onreadystatechange = function(){
      if(xhr.readyState == 4  && xhr.status == 200){
          if(p_setting.dataType == "json"){
         p_setting.success(JSON.parse(xhr.responseText)); 
          }else {
            p_setting.success(xhr.responseText); 
          }
        }
   }
   xhr.send();
}
f_ajax({
    method:"get",
    url:"data.json",
    dataType:"json",
    success:function(rslt){
        console.log("화긴:",rslt);
    }
})
</script>

정리

<!DOCTYPE html>
<meta charset="UTF-8">
<body>
    <div id="disp"></div>
    <input type="button" value="누르숑" onclick="f_ajax()">
</body>
<script>
var vdisp = document.querySelector("#disp");
var $ = {};  // 네임스페이스용 빈 객체
$.ajax=function(p_setting){   // 매개변수를 flexible하게 사용하기 위해 json사용
    var xhr = new XMLHttpRequest(); // 항상 지역변수로 쓸 것!
   xhr.open(p_setting.method,p_setting.url,false); 
   xhr.onreadystatechange = function(){
      if(xhr.readyState == 4  && xhr.status == 200){
          if(p_setting.dataType == "json"){
            p_setting.success(JSON.parse(xhr.responseText)); 
          }else {
            p_setting.success(xhr.responseText); 
          }
        }
   }
   xhr.send();
}
$.ajax({
    method:"get",
    url:"data.json",
    dataType:"text",
    // 오해가 있는데 이번에 잘 이해하길, 이미받은 데이터를 JSON.parse 할거냥?
    success:function(rslt){
        console.log("화긴:",rslt);
    }
})
</script>
profile
Johannes

0개의 댓글