vue中用Ajax请求

http>index.js  封装Ajax

function get( url, fn){
  // 原生ajax

  const xhr = new XMLHttpRequest();
  xhr.open("GET", url, true); // true 异步 false 同步
  xhr.send();



  xhr.onreadystatechange = function () {
    if (xhr.readyState == 4) {
      if (xhr.status == 200) {
        console.log("结果是:", xhr.responseText);
        let obj= JSON.parse( xhr.responseText );
        console.log(obj);
        
        // 0-----------------返回值怎么办?----
        // return 123;
        fn(obj)

      } else {
        console.log("请求失败", xhr.status);
      }
    }
  };


  
}

export default {
    get
};

原生 home.vue  请求数据        原生--->jq写法回调写法




直接使用jq category.vue



jq【回调写法】 --> promise 【.then().then() 同步表达 -避免回调地狱】 user.vue



jq---封装的jq方法

import $ from "jquery";

function myAjax(url){

    return new Promise((resolved,rejected)=>{

        $.get(url,x=>{
            resolved(x);
        })  
    })  

}


export default myAjax;

你可能感兴趣的:(前端)