封装一个ajaxget请求方法,以备不时之需

function ajaxGet(url) {
    return new Promise((resolve, reject) => {
      let xhr = new XMLHttpRequest();
      xhr.open("GET",url,true);
      xhr.send();
      xhr.onreadystatechange = () => {
        // console.log(‘xhr.readyState‘, xhr.readyState)
        switch (xhr.readyState) {
          case 4:
            // 请求成功
            let responseStr = xhr.response;
            let response = null;
            try {
              response = JSON.parse(responseStr)
            } catch(e) {
              response = null;
            }
            // console.log(‘response‘, response)
            if(response) {
              resolve(response)
            }else {
              reject(‘无数据‘)
            }
            break;
          default:
            break;
        }
      }
    })
}



function getBaseFile() {
    ajaxGet(‘url‘).then((res)=>{
        console.log(‘res‘, res)
        if(res.code == 200) {
            
        }
    })
}

getBaseFile()

 

封装一个ajaxget请求方法,以备不时之需

上一篇:Kubernetes Logs 如何获取kube-system pod的日志


下一篇:JS之路:Promise