当前位置: 首页 > news >正文

Ajax原理笔记

1. 后端如何把数据传给前端?

后端通常通过 HTTP 接口(API) 把数据传给前端,一般流程如下:

(1)后端提供 API 接口

后端使用 Spring Boot 开发 API,通常返回 JSON 数据
例如,在 Controller 层定义一个接口,返回商品列表:

@RestController
@RequestMapping("/api/products")
public class ProductController {

    @GetMapping("/list")
    public List<Product> getProductList() {
        List<Product> products = new ArrayList<>();
        products.add(new Product(1, "苹果", 5.5));
        products.add(new Product(2, "香蕉", 3.2));
        return products;
    }
}
 

💡 解释

  • @RestController:返回 JSON 数据。
  • @GetMapping("/list"):定义一个 GET 请求的 API。
  • 返回的是一个 List<Product>,Spring Boot 会自动序列化为 JSON。

这个 API 的访问地址是:

http://localhost:8080/api/products/list

返回的 JSON 数据:

[
  { "id": 1, "name": "苹果", "price": 5.5 },
  { "id": 2, "name": "香蕉", "price": 3.2 }
]


2. 前端如何获取后端数据?(axios 封装 Ajax 请求)

前端通常使用 Axios 发送 AJAX 请求来获取数据。

(1)安装 Axios

如果你使用的是 Vue 项目,先安装 Axios:

npm install axios

(2)封装 axios 请求

可以在 utils/request.js 中封装 Axios:

import axios from 'axios';

// 创建 axios 实例
const request = axios.create({
  baseURL: 'http://localhost:8080/api', // 后端 API 地址
  timeout: 5000 // 请求超时时间
});

// 请求拦截器(可选)
request.interceptors.request.use(config => {
  console.log("请求发送:", config);
  return config;
}, error => {
  return Promise.reject(error);
});

// 响应拦截器(可选)
request.interceptors.response.use(response => {
  console.log("响应数据:", response.data);
  return response.data;
}, error => {
  return Promise.reject(error);
});

export default request;

(3)前端调用后端 API

在 Vue 组件中(例如 ProductList.vue),使用封装的 axios 请求数据:

 

<template>
  <div>
    <h2>商品列表</h2>
    <ul>
      <li v-for="product in products" :key="product.id">
        {{ product.name }} - ¥{{ product.price }}
      </li>
    </ul>
  </div>
</template>

<script>
import request from "@/utils/request";

export default {
  data() {
    return {
      products: []
    };
  },
  mounted() {
    this.fetchProducts();
  },
  methods: {
    async fetchProducts() {
      try {
        const response = await request.get("/products/list");
        this.products = response; // 赋值给前端的 products
      } catch (error) {
        console.error("获取商品列表失败:", error);
      }
    }
  }
};
</script>
 


🔥 总结:

  1. 后端提供 API(Spring Boot @RestController 返回 JSON)。
  2. 前端封装 axios(统一管理 API 请求)。
  3. 前端调用 API(在 Vue 组件中使用 axios.get() 请求数据)。
  4. 数据绑定到页面(使用 v-for 循环渲染列表)。

相关文章:

  • JDBC数据库连接池技术详解——从传统连接方式到高效连接管理
  • 零拷贝分析
  • LeetCode热题100JS(49/100)第九天|199|114|105|437|236
  • undo log ,redo log 和binlog的区别?
  • 使用 yum 命令安装 MariaDB 指南
  • 安卓edge://inspect 和 chrome://inspect调试移动设备上的网页
  • 瑞幸需要宇树科技
  • UNION,UNION ALL 的详细用法
  • 【leetcode hot 100 437】路径总和Ⅲ
  • Typora 使用教程(标题,段落,字体,列表,区块,代码,脚注,插入图片,表格,目录)
  • 什么是广播系统语言传输指数 STIPA
  • CCF CSP 第30次(2023.05)(1_仓库规划_C++)
  • 关于运行 npm run serve/dev 运行不起来,node_modules Git忽略不了等(问题)
  • 冰羚杂谈(四)上下游对齐工作节奏
  • 基于SpringBoot+Vue3实现的宠物领养管理平台功能一
  • 算法竞赛-基础算法-位运算
  • 基于cat1的多传感器融合的贵重资产管理解决方案项目说明书
  • 基于Django的交通指示图像识别分析系统
  • Unity WebGL IIS报错无法使用
  • LeetCode 解题思路 19(Hot 100)
  • 秦洪看盘|交易新逻辑,银行股成A股稳定器
  • 兰州大学教授安成邦加盟复旦大学中国历史地理研究所
  • 习近平出席中拉论坛第四届部长级会议开幕式并发表主旨讲话
  • 明查|印度空军“又有一架战机被巴基斯坦击落,飞行员被俘”?
  • 欧阳娜娜携家人回江西探亲,受聘为江西吉安文化旅游大使
  • 今起公开发售,宁德时代将于5月20日在港股上市