axios获取数据

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);
});

你可能感兴趣的:(axios获取数据)