axios获取数据

2019-07-29  本文已影响0人  没了提心吊胆的稗子

Promise封装ajax

function ajax({url='', type='get', dataType='json'}) {
    return new Promise((resolve, reject)=>{
        let xhr = new XMLHttpRequest;
        xhr.open(type, url, true);
        xhr.responseType = dataType;
        xhr.onload = function () { // onload===xhr.readState=4&&xhr.status=200
            if(xhr.status === 200){
                (xhr.response);
            }
        };
        xhr.onerror = function (err) {
          reject(err);
        };
        xhr.send();
    })
}

axios获取数据 获取到的数据是res.data

axios.get('carts.json').then( res => { // 成功的回调
  // console.log(res);
  this.products = res.data;
},  err => { // 失败的回调
  console.log(err);
});
上一篇下一篇

猜你喜欢

热点阅读