promise-ajax.js
function ajax({url='xxx', type="get", dataType="json"}) {
return new Promise((resolve, reject) => {
let xhr = new XMLHttpRequest();
xhr.open(type, url, true);
xhr.responseType = dataType;
xhr.onload = function () {
if(xhr.status == 200){
resolve(xhr.response)
}else{
reject('not found');
}
};
xhr.onerror = function (err) {
reject(err)
};
xhr.send();
})
}
使用
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<body>
<div id="app"></div>
<script src="node_modules/vue/dist/vue.js"></script>
<script src="promise-ajax.js"></script>
<script>
let vm = new Vue({
el: '#app',
created(){
ajax({url: './carts.json'}).then((res)=>{
console.log(res)
}, (err)=>{
console.log(err)
})
},
data: {
products: []
}
})
</script>
</body>
</html>