ajax 和 axios 的使用和区别

在开始之前先看一下代码:

 ajax:

  $.ajax{

    url: ‘接口地址’,

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

    dataType: ‘json’,

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

      ’username’ : ‘hermit’,

      ’password’ : ‘a123’

    },

    success : function response) {

      console.logresponse); // 请求返回的数据

    }

  })

 axios:

  axios{

    url: ‘接口地址’,

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

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

    data: {

      ‘username’ : ‘hermit’,

      ’password’ : ‘a123’

    }

  }).then functionresponse){ // 请求正确返回的数据

    console.logresponse);

    console.logresponse.data);

  }).catch functionerror) { // 请求错误返回的数据

    console.logerror);

  })

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

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

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

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

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

  btnvalue){
    let postData = qs.stringify{
      weixin: value
    })
    let api = ‘http://tp.xxxxxxxxx.com/index.php/index/index/checkweixin’;
    axios.postapi, postData)
    .thenfunctionres) { //请求成功返回的数据
      console.log’==00000′,res.data.code);
      ifres.data.code == 0){
        $’.popup-box’).css{
          ’display’:’block’
        })
        $’.popup-a1′).css{
          ’display’:’block’
        })
        $’.numbering>span’).htmlthat.value);

      }else{
        $’.popup-box’).css{
          ’display’:’block’
        )
        $’.popup-a2′).css{
          ’display’:’block’
        })
        $’.numbering-a>span’).htmlthat.value);
      }
    })
    .catchfunctionerr){
      console.log’err==>>’, err); //请求失败返回的数据
    })
  }

在vue中使用 axios 请参考我的另外一篇博客:vue 使用 axios

   

Published by

风君子

独自遨游何稽首 揭天掀地慰生平