Jquery、Vue 、Ajax、axios、Fetch区别

Jquery、Vue



jQuery Ajax 与 Vue 中 Axios 的对比


csharp 复制代码
## Ajax (get请求)
$.ajax({
  url: '/api/data',
  method: 'GET',
  success: function(response) {
    console.log(response);
  },
  error: function(error) {
    console.error(error);
  }
});
## promise风格的Axios 
#   axios get请求
axios.get('/api/data')
  .then(response => {
    console.log(response.data);
  })
  .catch(error => {
    console.error(error);
  });
## Ajax  post请求
$.ajax({
  url: '/api/data',
  method: 'POST',
  data: { name: 'John', age: 30 },
  success: function(response) {
    console.log(response);
  }
});
## axios post 请求
axios.post('/api/data', { name: 'John', age: 30 })
  .then(response => {
    console.log(response.data);
  });

Axios 独有的拦截器功能,类似于.Core 中的中间件

csharp 复制代码
// 请求拦截器
axios.interceptors.request.use(config => {
  // 在发送请求前做些什么
  config.headers.Authorization = 'Bearer token';
  return config;
});

// 响应拦截器
axios.interceptors.response.use(
  response => {
    // 对响应数据做点什么
    return response;
  },
  error => {
    // 对响应错误做点什么
    return Promise.reject(error);
  }
);


const source = axios.CancelToken.source();

axios.get('/api/data', {
  cancelToken: source.token
}).catch(thrown => {
  if (axios.isCancel(thrown)) {
    console.log('Request canceled', thrown.message);
  } else {
    // 处理其他错误
  }
});

// 取消请求
source.cancel('Operation canceled by the user.');
csharp 复制代码
##  在Vue中使用
// 通常在 main.js 中全局配置
import axios from 'axios';

axios.defaults.baseURL = 'https://api.example.com';
axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;

// 在组件中使用
export default {
  data() {
    return {
      users: []
    }
  },
  created() {
    axios.get('/users')
      .then(response => {
        this.users = response.data;
      })
      .catch(error => {
        console.error(error);
      });
  }
}
相关推荐
大龄码农有梦想8 小时前
Vue + BPMN.js + Camunda:搭建企业级流程设计器完整实践
javascript·vue.js·流程设计器·bpmn.js·bpmn·流程审批·工作流设计器
岁岁种桃花儿12 小时前
Vue核心语法第一篇:Vue是什么?
前端·javascript·vue.js
你挚爱的强哥14 小时前
【chromeDownload】自定义组件:多用于登录框底部提供下载Chrome谷歌浏览器的链接
前端·vue.js·chrome
daols8814 小时前
vue 甘特图 vxe-gantt 任务条拖拽自动更新日期
javascript·vue.js·甘特图
java1234_小锋1 天前
Vue3专题 - 组件基础
vue.js·vite
云水一下1 天前
零基础玩转bWAPP靶场(四十六):XSS - Reflected (AJAX/JSON)
web安全·ajax·json·xss·bwapp·reflected
阿懂在掘金1 天前
同一份弹窗我重构了三次:从 v-model 地狱到路由式调用,终于治好了模板臃肿
前端·vue.js·前端框架
starzy19901 天前
Spark 核心之自定义累加器以及版本对比变化深度剖析
大数据·ajax·spark
小锋java12342 天前
【技术专题】Vue3 - 生命周期
vue.js·vite
淘源码d2 天前
从0到1搭建医院随访系统:模块拆解 + 技术选型 + 部署方案
数据库·vue.js·源码·随访