vue 几种ajax

1.原生XMLHTTPREQUEST:这里不做解释

2.window下的fetch(基于promise)

它响应里有个json()方法,这也是个promise,所以也得使用.then。调用这个方法就可以得到请求的东西了。

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

3.vue-resourse(已经停更)

引入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创建一个axios实例
const ajax = axios.create({
  baseURL: 'https://jsonplaceholder.typicode.com'
});
//  拦截器,拦截请求, 只要一有请求,就会执行use里的方法, config就是请求的参数
ajax.interceptors.request.use((config) => {
  // 可以在这里更改请求参数,一般用于获取web本地存储的用户token
  config.headers['xxx-token'] = 'adsfqsaddggag'; //headers、body都行
  vm.isLoading = true;   //v-if来判断提示加载中
  return config;
});
//  拦截器,拦截响应,只要一有ajax数据返回,就会执行use里的方法
ajax.interceptors.response.use((resp) => {
  console.log('xxxx', resp)
  // 在这里可以统一处理数据异常,但是前提是:后端数据足够规范!!!!
  vm.isLoading = false;
  if (resp.status === 200) {
    return resp.data       //到时候请求的时候,直接拿到data(不含status那些)
  } else {
    alert('出错了!')
  }
});
// 把ajax赋值给Vue.prototype.$http
//这样在vue的实例里就可以通过this.$http来调用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();
  }
})
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • ## 框架和库的区别?> 框架(framework):一套完整的软件设计架构和**解决方案**。> > 库(lib...
    Rui_bdad阅读 3,171评论 1 4
  • PS:转载请注明出处作者: TigerChain地址: https://www.jianshu.com/p/218...
    TigerChain阅读 26,541评论 5 70
  • _________________________________________________________...
    fastwe阅读 1,496评论 0 0
  • # 传智播客vue 学习## 1. 什么是 Vue.js* Vue 开发手机 APP 需要借助于 Weex* Vu...
    再见天才阅读 3,817评论 0 6
  • 春天到了 它们拼命的生长 每天都不重样 某日的一天 骑着单车 行驶在校园的街道上 不由自主的抬着头 仰望天空 然而...
    Goodnights阅读 245评论 0 0

友情链接更多精彩内容