一、目的

需要实现的功能有包括:

  • 从服务器发送请求,获取图书列表并渲染
  • 添加新图书
  • 编辑现有图书信息
  • 删除图书
  • 以上每一步都实现与服务器存储数据同步更改

二、基础配置

引入Axios库:

<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>

三、核心功能实现

1. 获取图书列表并渲染

function getbooklist() {axios({url: 'http://hmajax.itheima.net/api/books',params: {creator: 'evergreen'}}).then(result => {const booklist = result.data.dataconst htmlstr = booklist.map((item, index) => {return `<li class="hei"><div class="number ha">${index + 1}</div><span></span><div class="book ha">${item.bookname}</div><span></span><div class="authors ha">${item.author}</div><span></span><div class="publish ha">${item.publisher}</div><span></span><div class="movement ha" id="${item.id}"><div class="btn1">删除</div><div class="btn2">修改</div></div></li>`}).join('')document.querySelector('ul').innerHTML = htmlstr})
}

关键点:

  • 使用axios发起GET请求
  • 通过map方法将数据转换为HTML字符串
  • 使用模板字符串动态插入数据
  • 最后将生成的HTML插入到页面中

2. 添加新图书

// 添加按钮点击事件
document.querySelector('.add').addEventListener('click', () => {editmodal.show()flag = 1 // 设置标志位为添加模式
})// 保存按钮点击事件
document.querySelector('.save').addEventListener('click', (e) => {editmodal.hide()if (flag) { // 添加模式const bookname = document.querySelector('.bookname').valueconst author = document.querySelector('.author').valueconst publisher = document.querySelector('.publisher').valueaxios({url: `http://hmajax.itheima.net/api/books`,method: 'POST',data: {bookname,author,publisher,creator: 'evergreen'}}).then(() => {getbooklist() // 刷新列表// 清空输入框document.querySelector('.bookname').value = ''document.querySelector('.author').value = ''document.querySelector('.publisher').value = ''})}
})

关键点:

  • 使用POST方法提交新数据
  • 请求体包含图书信息和创建者标识
  • 成功后刷新列表并清空表单

3. 编辑现有图书

// 修改按钮点击事件
ul.addEventListener('click', (e) => {if (e.target.className === 'btn2') {flag = 0 // 设置标志位为编辑模式const theid = e.target.parentNode.ideditmodal.show()// 获取图书详情并填充表单axios({url: `http://hmajax.itheima.net/api/books/${theid}`,}).then(result => {const bookobj = result.data.data// 自动填充表单document.querySelector('.bookname').value = bookobj.booknamedocument.querySelector('.author').value = bookobj.authordocument.querySelector('.publisher').value = bookobj.publisherdocument.querySelector('.id').value = bookobj.id})}
})// 保存修改
document.querySelector('.save').addEventListener('click', (e) => {editmodal.hide()if (!flag) { // 编辑模式const bookname = document.querySelector('.bookname').valueconst author = document.querySelector('.author').valueconst publisher = document.querySelector('.publisher').valueconst theid = document.querySelector('.id').valueaxios({url: `http://hmajax.itheima.net/api/books/${theid}`,method: "put",data: {bookname,author,publisher,creator}}).then(() => {getbooklist() // 刷新渲染列表// 清空输入框//清空输入框const inputs = document.querySelectorAll('.bookname, .author, .publisher');// 清空值inputs.forEach(input => {input.value = ""; // 设为空字符串});})}
})

完整代码:

<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title><link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.7/dist/css/bootstrap.min.css" rel="stylesheet"integrity="sha384-LN+7fdVzj6u52u30Kp6M/trliBMCMKTyK833zpbD+pXdCLuTusPj697FH4R/5mcr" crossorigin="anonymous"><style>.nav {position: relative;height: 40px;width: 600px;}.nav h2 {left: 0;position: absolute;padding: 0;margin: 0;}.nav .add {position: absolute;right: 0;float: right !important;color: #fff;padding: 0;margin-top: 10px;height: 25px;width: 60px;line-height: 25px;text-align: center;background-color: rgb(58, 171, 240);border-radius: 3px;cursor: pointer;}header {background-color: gray;color: #e0e0e0;}.hei {width: 600px;font-family: 'Courier New', Courier, monospace;height: 60px;line-height: 60px;}.ha {display: inline-block;text-align: center;border-left: 1px #fff solid;}.number {display: inline-block;width: 60px;}.book {display: inline-block;width: 120px;}.authors {display: inline-block;width: 100px;}.publish {display: inline-block;width: 120px;}.movement {display: inline-block;width: 150px;}ul {padding: 0;}li {list-style: none;border-bottom: 1px solid gray;}.btn1,.btn2 {display: inline-block;height: 30px;line-height: 30px;width: 50px;cursor: pointer;border-radius: 3px;background-color: #e9e9e9;}.btn1:hover,.btn2:hover {color: #fff;}.modal .modal-dialog .modal-content {height: 390px;}.modal .modal-dialog .modal-content input {margin: 10px 25px;}.modal-footer {margin-top: 20px;}.modal-content span {margin-left: 20px;}</style>
</head><body><!-- Button trigger modal --><!-- Modal --><div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true"><div class="modal-dialog"><div class="modal-content"><div class="modal-header"><h1 class="modal-title fs-5" id="exampleModalLabel">Modal title</h1><button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button></div><br class="modal-body"><input type="text" class="id" hidden><span>书名:</span><input type="text" class="bookname"><span>作者:</span><input type="text" class="author"><span>出版社:</span><input type="text" class="publisher"><div class="modal-footer"><button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button><button type="button" class="btn btn-primary save">Save changes</button></div></div></div></div></div><section><div class="nav"><h2>图书管理</h2><button type="button" class="add">添加</button></div><header class="hei"><div class="number ha">序号</div><span></span><div class="book ha">书名</div><span></span><div class="authors ha">作者</div><span></span><div class="publish ha">出版社</div><span></span><div class="movement ha">操作</div></header><ul><li class="hei" id="1"><div class="number ha">1</div><span></span><div class="book ha">荒原狼</div><span></span><div class="authors ha">德·黑塞</div><span></span><div class="publish ha">人民出版社</div><span></span><div class="movement ha"><div class="btn1">删除</div><div class="btn2 ">修改</div></div></li></ul><script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.7/dist/js/bootstrap.bundle.min.js"integrity="sha384-ndDqU0Gzau9qJ1lfW4pNLlhNTkCfHzAVBReH9diLvGRem5+R9g2FzA8ZGN954O5Q"crossorigin="anonymous"></script><script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script><script>//从服务器获取信息const creator = 'evergreen'let flag = 0function getbooklist() {axios({url: 'http://hmajax.itheima.net/api/books',params: {creator: 'evergreen'}}).then(result => {console.log(result);const booklist = result.data.dataconst htmlstr = booklist.map((item, index) => {return `<li class="hei"><div class="number ha">${index + 1}</div><span></span><div class="book ha">${item.bookname}</div><span></span><div class="authors ha">${item.author}</div><span></span><div class="publish ha">${item.publisher}</div><span></span><div class="movement ha" id="${item.id}"><div class="btn1">删除</div><div class="btn2">修改</div></div></li>`}).join('')console.log(htmlstr);document.querySelector('ul').innerHTML = htmlstr})}getbooklist()//弹框处理const editDom = document.querySelector('.fade')const editmodal = new bootstrap.Modal(editDom)const ul = document.querySelector('ul')document.querySelector('.add').addEventListener('click', () => {editmodal.show()flag = 1})ul.addEventListener('click', (e) => {if (e.target.className === 'btn1') {const bookid = e.target.parentNode.idconsole.log(bookid);axios({url: `http://hmajax.itheima.net/api/books/${bookid}`,method: 'delete'}).then(() => {getbooklist()})}if (e.target.className === 'btn2') {flag = 0const theid = e.target.parentNode.idconsole.log(theid);editmodal.show()//从服务器取出信息渲染页面axios({url: `http://hmajax.itheima.net/api/books/${theid}`,}).then(result => {console.log(result);/* 1.普通传值const showbookname=document.querySelector('.bookname')const showauthor=document.querySelector('.author')const showpublisher=document.querySelector('.publisher')showbookname.value=result.data.data.booknameshowauthor.value=result.data.data.authorshowpublisher.value=result.data.data.publisher*///遍历传值//数据类型是对象,取出值的数组,利用变量关系渲染const bookobj = result.data.dataconst keys = Object.keys(bookobj)console.log(keys)keys.forEach(key => {document.querySelector(`.${key}`).value = bookobj[key]})})}})//随机数函数-随机生成idfunction getRandomInt(min, max) {return Math.floor(Math.random() * (max - min + 1)) + min;}document.querySelector('.save').addEventListener('click', (e) => {editmodal.hide()//渲染到页面//传到服务器if (flag) {const bookname = document.querySelector('.bookname').valueconst author = document.querySelector('.author').valueconst publisher = document.querySelector('.publisher').valueconst id = getRandomInt(100000, 999999)console.log('win');const inputs = document.querySelectorAll('.bookname, .author, .publisher');// 清空值inputs.forEach(input => {input.value = ""; // 设为空字符串});axios({url: `http://hmajax.itheima.net/api/books`,method: 'POST',data: {bookname,author,publisher,creator}}).then(() => {getbooklist()})}if (!flag) {//将数据从框中取出// 获取所有输入框const bookname = document.querySelector('.bookname').valueconst author = document.querySelector('.author').valueconst publisher = document.querySelector('.publisher').valueconst theid = document.querySelector('.id').value//清空输入框const inputs = document.querySelectorAll('.bookname, .author, .publisher');// 清空值inputs.forEach(input => {input.value = ""; // 设为空字符串});axios({url: `http://hmajax.itheima.net/api/books/${theid}`,method: "put",data: {bookname,author,publisher,creator}}).then(() => {getbooklist()})}})</script></section>
</body></html>

关键点:

  • 使用PUT方法更新数据
  • 需要传入图书ID以确定修改哪条记录
  • 先获取原始数据填充表单,修改后提交

四、遇到的问题与解决方案

  1. 表单复用问题

    • 同一个表单既用于添加也用于编辑,但添加书籍会渲染新数据,而编辑只在原数据上修改
    • 解决方案:使用flag变量区分模式
  2. 数据刷新问题

    • 增删改操作后页面数据不同步
    • 解决方案:操作成功后重新调用getbooklist()
  3. 表单清空问题

    • 操作后表单内容残留
    • 解决方案:手动清空输入框

本案例参考: b站黑马程序员AJAX学习视频16-25集实战案例

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如若转载,请注明出处:http://www.pswp.cn/pingmian/88935.shtml
繁体地址,请注明出处:http://hk.pswp.cn/pingmian/88935.shtml
英文地址,请注明出处:http://en.pswp.cn/pingmian/88935.shtml

如若内容造成侵权/违法违规/事实不符,请联系英文站点网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

SQLlite下载以及简单使用

SQLite Download Page cd D:\WK\2025\StudentManagerSystem\sqlite D: entManagerSystem\sqlite>sqlite3.exe 所建库的名字.db 一&#xff1a;命令 <1>打开某个数据库文件中 sqlite3 test.db<2>查看所有的命令介绍(英文) .help<3>退出当前数据库系统 .qu…

函数柯里化详解

一、函数柯里化&#xff1a; 是一种高阶函数技术&#xff0c;它将一个多参数函数转换为一系列单参数函数的链式调用。 核心概念 定义&#xff1a;将一个函数 f(a, b, c) 转换为 f(a)(b)© 的形式 **本质&#xff1a;**通过闭包保存参数&#xff0c;实现分步传参 关键特征&a…

C++11:constexpr 编译期性质

C11&#xff1a;constexpr & 编译期性质常量表达式 constexpr变量IiteralType函数自定义字面量参数匹配与重载规则静态断言常量表达式 constexpr const expression常量表达式&#xff0c;是C11引入的新特性&#xff0c;用于将表达式提前到编译期进行计算&#xff0c;从而减…

【每天一个知识点】多模态信息(Multimodal Information)

常用的多模态信息&#xff08;Multimodal Information&#xff09;指的是来源于多种感知通道/数据类型的内容&#xff0c;这些信息可以被整合处理&#xff0c;以提升理解、推理与生成能力。在人工智能和大模型系统中&#xff0c;典型的多模态信息主要包括以下几类&#xff1a;✅…

iOS 抓包工具精选对比:不同调试需求下的工具适配策略

iOS 抓包痛点始终存在&#xff1a;问题不是“抓不抓”&#xff0c;而是“怎么抓” 很多开发者都遇到过这样的情况&#xff1a; “接口没有返回&#xff0c;连日志都没打出来”“模拟器正常&#xff0c;真机无法请求”“加了 HTTPS 双向认证&#xff0c;抓不到了”“明明设置了 …

图像修复:深度学习实现老照片划痕修复+老照片上色

第一步&#xff1a;介绍 1&#xff09;GLCIC-PyTorch是一个基于PyTorch的开源项目&#xff0c;它实现了“全局和局部一致性图像修复”方法。该方法由Iizuka等人提出&#xff0c;主要用于图像修复任务&#xff0c;能够有效地恢复图像中被遮挡或损坏的部分。项目使用Python编程语…

css 边框颜色渐变

border-image: linear-gradient(90deg, rgba(207, 194, 195, 1), rgba(189, 189, 189, 0.2),rgba(207, 194, 195, 1)) 1;

本地 LLM API Python 项目分步指南

分步过程 需要Python 3.9 或更高版本。 安装 Ollama 并在本地下载 LLM 根据您的操作系统&#xff0c;您可以从其网站下载一个或另一个版本的 Ollama 。下载并启动后&#xff0c;打开终端并输入以下命令&#xff1a; ollama run llama3此命令将在本地拉取&#xff08;下载&…

日本的所得税计算方式

✅ 【1】所得税的计算步骤&#xff08;概要&#xff09; 日本的所得税大致按照以下顺序来计算&#xff1a; 1️⃣ 统计收入&#xff08;销售额、工资等&#xff09; 2️⃣ 扣除必要经费等&#xff0c;得到「所得金額」 3️⃣ 扣除各类「所得控除」&#xff08;所得扣除&#xf…

【langchain4j篇01】:5分钟上手langchain4j 1.1.0(SpringBoot整合使用)

目录 一、环境准备 二、创建项目、导入依赖 三、配置 application.yml 四、注入Bean&#xff0c;开箱即用 五、日志观察 一、环境准备 首先和快速上手 Spring AI 框架一样的前置条件&#xff1a;先申请一个 apikey &#xff0c;此部分步骤参考&#xff1a;【SpringAI篇01…

js运算符

运算符 jarringslee*赋值运算符 - / 对变量进行赋值的运算符&#xff0c;用于简化代码。左边是容器&#xff0c;右边是值一元运算符正号 符号- 赋予数据正值、负值自增 自减– 前置和后置&#xff1a;i和i&#xff1a;一般情况下习惯使用后置i&#xff0c;两者在单独…

next.js 登录认证:使用 github 账号授权登录。

1. 起因&#xff0c; 目的: 一直是这个报错。2. 最终效果&#xff0c; 解决问题&#xff0c;能成功登录、体验地址&#xff1a;https://next-js-gist-app.vercel.app/代码地址&#xff1a; https://github.com/buxuele/next-js-gist-app3. 过程: 根本原因: github 的设置&…

深入理解设计模式:原型模式(Prototype Pattern)

在软件开发中&#xff0c;对象的创建是一个永恒的话题。当我们需要创建大量相似对象&#xff0c;或者对象创建成本较高时&#xff0c;传统的new操作符可能不是最佳选择。原型模式&#xff08;Prototype Pattern&#xff09;为我们提供了一种优雅的解决方案——通过克隆现有对象…

Rocky Linux 9 源码包安装php8

Rocky Linux 9 源码包安装php8大家好&#xff0c;我是星哥&#xff01;今天咱们不聊yum一键安装的“快餐式”部署&#xff0c;来点儿硬核的——源码编译安装PHP 8.3。为什么要折腾源码&#xff1f;因为它能让你深度定制PHP功能、启用最新特性&#xff0c;还能避开系统默认源的版…

Django母婴商城项目实践(四)

4、路由规划与设计 1、概述 介绍 路由称为 URL(Uniform Resource Locator,统一资源定位符),也称为 URLconf,对互联网上得到的资源位置和访问方式的一种简洁表示,是互联网上标准梓源的地址。互联网上的每个文件都有一个唯一的路由,用于指出网站文件的路由位置,也可以理…

论文阅读:arxiv 2025 A Survey of Large Language Model Agents for Question Answering

https://arxiv.org/pdf/2503.19213 https://www.doubao.com/chat/12038636966213122 A Survey of Large Language Model Agents for Question Answering 文章目录速览论文翻译面向问答的大型语言模型代理综述摘要一、引言速览 这篇文档主要是对基于大型语言模型&#xff08;…

ONNX 是什么

ONNX 是什么&#xff1f; ONNX&#xff0c;全称 Open Neural Network Exchange&#xff0c;是微软和 Facebook&#xff08;现在的 Meta&#xff09;联合发起的一个开放的神经网络模型交换格式。简单理解&#xff1a;ONNX 是一个通用的「AI 模型存档格式」。用 PyTorch、TensorF…

【Python3】掌握DRF核心装饰器:提升API开发效率

在 Django REST Framework (DRF) 中&#xff0c;装饰器&#xff08;Decorators&#xff09;通常用于视图函数或类视图&#xff0c;以控制访问权限、请求方法、认证等行为。以下是 DRF 中常用的装饰器及其功能说明&#xff1a; 1. api_view 用途: 用于基于函数的视图&#xff0c…

Datawhale AI 夏令营第一期(机器学习方向)Task2 笔记:用户新增预测挑战赛 —— 从业务理解到技术实现

Datawhale AI夏令营第一期&#xff08;机器学习方向&#xff09;Task2笔记&#xff1a;用户新增预测挑战赛——从业务理解到技术实现 一、任务核心&#xff1a;业务与技术的“翻译” 本次Task聚焦“用户新增预测挑战赛”的核心逻辑&#xff0c;核心目标是锻炼“将业务问题转化为…

【人工智能】华为昇腾NPU-MindIE镜像制作

本文通过不使用官方镜像,自己在910b 进行华为mindie的镜像制作,可离线安装部署。 硬件:cann 8.0 1. 部署参考文档: 安装依赖-安装开发环境-MindIE安装指南-MindIE1.0.0开发文档-昇腾社区 2. 参数说明文档:https://www.hiascend.com/document/detail/zh/mindie/100/min…