ajax和axios的区别和联系

ajax:

  $.ajax({

    url: 接口地址,

    type: get, //或者post   请求类型

    dataType: json,

    data: { // 要发送的请求参数

      username : 张三,

      password : 123

    },

    success : function (response) {

      console.log(response); // 请求返回的数据

    }

  })

 axios:

  axios({

    url: 接口地址,

    method: get, //或者 post 请求类型

    responseType: json, //默认格式,如果就是 json 格式可以不写

    data: {

      username : 张三,

      password : 123

    }

  }).then( function(response){ // 请求正确返回的数据

    console.log(response);

    console.log(response.data);

  }).catch( function(error) { // 请求错误返回的数据

    console.log(error);

  })

 两者其实并没有太大的区别,在写法上大致相同。

 其实axios是通过 promise 实现对 ajax 技术的一种封装。就像 ajax 是 通过 jQuery 来封装一样。

 也就是说,jQuery 将请求技术进行了封装 变成了 ajax , 而 通过 promise 又把 ajax 进行封装就成了 axios。

 在现在的前端 mvvm 模式下 axios 更适合于数据请求。

  下面一段是在 vue 中使用的 axios 代码:

  btn(value){     let postData = qs.stringify({       name: value     })     let api = http://tp.xxxxxx;     axios.post(api, postData)     .then(function(res) { //请求成功返回的数据       console.log(==00000,res.data.code);     })     .catch(function(err){       console.log(err==>>, err); //请求失败返回的数据     })   }

经验分享 程序员 微信小程序 职场和发展