순수 javascript의 fetch 함수를 이용한 커스텀 비동기 ajax 함수
순수 javascript의 fetch 함수를 이용한 커스텀 비동기 ajax 함수
REDINFO
몇달 전 2024-01-20 19:57:01

순수 javascript 에서 ajax 통신을 할때 주로 XMLHttpRequest 또는 fetch 를 이용했을 것이다. XMLHttpRequest의 경우 현재도 많이 사용되는 방식이긴 하나 현재까지 와서는 이보다 더 강력한 fetch 함수를 많이 사용하고 있는 편이다. 

 

이번편은 fetch 함수를 이용한 커스텀 비동기 ajax 함수에 대해 알아보도록 하자 

 

※ 제공된 소스는 공식 제공되는 소스가 아니며 사용 시 오류가 발생될 수 있는점 참고 바랍니다. 
순수 javascript 로 만든 비동기 ajax 함수
async function ajax(url,type,params){
  /**
    - params참고
      => https://developer.mozilla.org/ko/docs/Web/API/fetch
  **/
  // URL파라미터 => OBJECT 변경 함수
  this.parseUrlParameters = function(url){
    if(/^(http|https):\/\/[^ "]+$/.test(url) !== true){
      url =  (document.location.protocol)+('//')+(document.location.host)+url;
    }
    const urlString = new URL(url);
    const urlSearchParams = new URLSearchParams(urlString.search);
    const params = {};
    urlSearchParams.forEach((value, key) => {
      params[key] = value;
    });
    return params;
  }

  // obj merge 
  this.objMerge = function (target, source) {
    for (const key in source) {
      if (source[key] instanceof Object && key in target) {
        deepMerge(target[key], source[key]);
      } else {
        Object.assign(target, { [key]: source[key] });
      }
    }
    return target;
  }  

  // ...초기화
  params = typeof params != 'object' ? {} : params;
  let request = {
    type : typeof type == 'undefined' || ['json','blob','text'].includes(type) == false ? 'json': type,
    params : typeof params != 'object' ? {} : params,
    url : '',
  };

  if(typeof url != 'string' || !url){ return false; }

  request.url = url;
  request.params.method = typeof params.method == 'undefined' || !typeof params.method ? 'GET':params.method;
  
  if( request.params.method == 'POST'){
    if( typeof request.params.body == 'object'){
      request.params.body = this.objMerge(this.parseUrlParameters(url),request.params.body);
    }
    else{
      request.params.body = this.parseUrlParameters(url);
    }
  }

  // 최종 결과
  let getResult = {};
  try{
    let response = await fetch(request.url,request.params);
    switch(type){
      case "json": getResult = await response.json(); break;
      case "blob": getResult = await response.blob(); break;
      case "text": getResult = await response.text(); break;
    }
  }catch(e){
    getResult = typeof message != 'undefined' ? e.message : e;
  }
  return getResult;
}

 

| 예제1. ajax 요청 후 json으로 응답받는 방법
<script>
window.onload = function(){
  // json
  ajax('/test/json.php?id=test&pw=1234').then(function(e){
      console.log(e);
  });    
}
</script>
| 예제2. ajax 요청 후 text로 응답받는 방법
<script>
window.onload = function(){
  // text
  ajax('/test/text.php?test=1&test444=3','text').then(function(e){
      console.log(e);
  });    
}
</script>
| 예제3. ajax 요청 후 blob 데이터로 응답받는 방법
<script>
window.onload = function(){
  // blob
  ajax('/test/blob.jpeg','blob').then(function(res){
    var blob = document.getElementById('blob');
    blob.setAttribute('src',URL.createObjectURL(res));
    blob.style.display = 'block';
  });    
}
</script>

<!-- 이미지 출력 -->
<img id="blob" src="" alt="" style="width:500px; height:auto;display:none;">

 

이 포스트글이 도움이 되었나요?
2
카테고리 연관글

Comment

댓글작성

0(500) | 1(30)