Manually encapsulate ajax based on Promise

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 () {
    
     // xhr.readState=4 xhr.status=200
      if(xhr.status == 200){
    
    
        resolve(xhr.response) //成功调用成功的方法
      }else{
    
    
        reject('not found');
      }
    };
    xhr.onerror = function (err) {
    
    
        reject(err) // 失败调用失败的方法
    };
    xhr.send();
  })
}

use

<!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>

Guess you like

Origin blog.csdn.net/lianghecai52171314/article/details/132415334