ajax 和 axios 的使用和區別


在開始之前先看一下代碼:

 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

   

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM