vue 幾種ajax

1.原生XMLHTTPREQUEST:這里不做解釋

2.window下的fetch(基于promise)

它響應(yīng)里有個json()方法,這也是個promise,所以也得使用.then。調(diào)用這個方法就可以得到請求的東西了。

fetch('https://jsonplaceholder.typicode.com/todos/1')
  .then(response => response.json())
  .then(json => console.log(json))

3.vue-resourse(已經(jīng)停更)

引入CDN或者npm后,會在vue的實例上多一個$http的對象,用于ajax請求, 聽說VUE不更新這個東西了。

this.$http.get('https://jsonplaceholder.typicode.com/todos/1')
    .then(resp => {
      console.log(resp);
      return resp.json()
    })
    .then(res => {
      console.log(res)
    })

4.axios(most popular)

安裝axios或者引入CDN,也是基于promise,如果你習慣用vue-resourse:

Vue.prototype.$http = axios;
this.$http.get(url)

將其綁定在Vue實例原型上即可使用。

axios配置路由攔截:

ajax.interceptors.request.use() 與ajax.interceptors.response.use()

// 使用axios.create創(chuàng)建一個axios實例
const ajax = axios.create({
  baseURL: 'https://jsonplaceholder.typicode.com'
});
//  攔截器,攔截請求, 只要一有請求,就會執(zhí)行use里的方法, config就是請求的參數(shù)
ajax.interceptors.request.use((config) => {
  // 可以在這里更改請求參數(shù),一般用于獲取web本地存儲的用戶token
  config.headers['xxx-token'] = 'adsfqsaddggag'; //headers、body都行
  vm.isLoading = true;   //v-if來判斷提示加載中
  return config;
});
//  攔截器,攔截響應(yīng),只要一有ajax數(shù)據(jù)返回,就會執(zhí)行use里的方法
ajax.interceptors.response.use((resp) => {
  console.log('xxxx', resp)
  // 在這里可以統(tǒng)一處理數(shù)據(jù)異常,但是前提是:后端數(shù)據(jù)足夠規(guī)范?。。?!
  vm.isLoading = false;
  if (resp.status === 200) {
    return resp.data       //到時候請求的時候,直接拿到data(不含status那些)
  } else {
    alert('出錯了!')
  }
});
// 把ajax賦值給Vue.prototype.$http
//這樣在vue的實例里就可以通過this.$http來調(diào)用ajax
Vue.prototype.$http = ajax;

5.jQuery的ajax:

引入jquery,ajax有請求類型type配置,默認為GET。

  $.ajax({
    url: 'https://jsonplaceholder.typicode.com/todos/1',
    type: "GET",
    success: function(resp) {
      console.log(resp)
    }
  })
jQuery的路由攔截配置:
$.ajaxSetup({
  beforeSend: function() {
    console.log('開始請求')
    $('.loading').show();    //提示加載中
  },
  complete: function() {
    $('.loading').hide();
  }
})
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • ## 框架和庫的區(qū)別?> 框架(framework):一套完整的軟件設(shè)計架構(gòu)和**解決方案**。> > 庫(lib...
    Rui_bdad閱讀 3,157評論 1 4
  • PS:轉(zhuǎn)載請注明出處作者: TigerChain地址: http://www.itdecent.cn/p/218...
    TigerChain閱讀 26,535評論 5 70
  • _________________________________________________________...
    fastwe閱讀 1,490評論 0 0
  • # 傳智播客vue 學習## 1. 什么是 Vue.js* Vue 開發(fā)手機 APP 需要借助于 Weex* Vu...
    再見天才閱讀 3,801評論 0 6
  • 春天到了 它們拼命的生長 每天都不重樣 某日的一天 騎著單車 行駛在校園的街道上 不由自主的抬著頭 仰望天空 然而...
    Goodnights閱讀 244評論 0 0

友情鏈接更多精彩內(nèi)容