hermit-gyqy

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

 ajax:

  $.ajax({

    url: \'接口地址\',

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

    dataType: \'json\',

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

      \'username\' : \'hermit\',

      \'password\' : \'a123\'

    },

    success : function (response) {

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

    }

  })

 axios:

  axios({

    url: \'接口地址\',

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

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

    data: {

      \'username\' : \'hermit\',

      \'password\' : \'a123\'

    }

  }).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({
      weixin: value
    })
    let api = \'http://tp.xxxxxxxxx.com/index.php/index/index/checkweixin\';
    axios.post(api, postData)
    .then(function(res) { //请求成功返回的数据
      console.log(\'==00000\',res.data.code);
      if(res.data.code == 0){
        $(\'.popup-box\').css({
          \'display\':\'block\'
        })
        $(\'.popup-a1\').css({
          \'display\':\'block\'
        })
        $(\'.numbering>span\').html(that.value);

      }else{
        $(\'.popup-box\').css({
          \'display\':\'block\'
        )
        $(\'.popup-a2\').css({
          \'display\':\'block\'
        })
        $(\'.numbering-a>span\').html(that.value);
      }
    })
    .catch(function(err){
      console.log(\'err==>>\', err); //请求失败返回的数据
    })
  }

 

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

   

 

分类:

技术点:

相关文章:

  • 2021-06-07
  • 2022-01-08
  • 2021-06-10
  • 2022-01-08
  • 2021-11-20
猜你喜欢
  • 2022-01-08
  • 2022-01-08
  • 2021-07-14
  • 2022-01-08
  • 2022-01-08
相关资源
相似解决方案