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

2020-12-22 18:27

阅读:623

标签:color   func   state   code   case   pre   else   read   cat   

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请求方法,以备不时之需

标签:color   func   state   code   case   pre   else   read   cat   

原文地址:https://www.cnblogs.com/wangkunlong/p/14148129.html


评论


亲,登录后才可以留言!