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

Axios方法完成图书管理页面完整版

一、目的

需要实现的功能有包括:

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

二、基础配置

引入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://.
http://.
http://.
http://.
http://.
http://.
http://.
http://.
http://.
http://.
http://.
http://.
http://.
http://.
http://.
http://.
http://.
http://.
http://.
http://.
http://.
http://.
http://.
http://.
http://.
http://.
http://.
http://.
http://.
http://.
http://www.dtcms.com/a/281661.html

相关文章:

  • Redis Desktop Manager(RDM)下载与安装使用教程
  • JavaScript中关于环境对象的拓展
  • 【Qt】 设计模式
  • Docker 镜像推送至 Coding 制品仓库超时问题排查与解决
  • 业务分析业务架构视角
  • 软件测试面试经历分享?
  • 在 SymPy 中精确提取三角函数系数的深度分析
  • LLM面试题目 3
  • 项目进度与预算脱节,如何进行同步管理
  • Linux部署Redis
  • 46. 携带研究材料(01背包二维数组)
  • Java程序员学从0学AI(五)
  • 发票查验接口的计费规则-核验成功返回参数
  • SpringBoot集成RocketMQ的两种方式
  • WGAS+WGCNA分析文章套路
  • LeetCode Hot100 【1.两数之和、2.两数相加、3.无重复字符的最长子串】
  • 动态数组:ArrayList的实现原理
  • 504网关超时可能是哪些原因导致?
  • web前端渡一大师课 01 事件循环
  • 【交流等效负载电阻的推导】
  • SpringBoot 项目搭建的 4 种常用方式,从入门到实践
  • 魔力宝贝归来虚拟机版怎么修复卡第一个任务
  • Kimi K2驱动Claude Code,稳定且低价
  • 入选《机器视觉》:视觉AI 生态链加速工业检测场景落地
  • MySQL数据库----函数
  • vue3:wangEditor使用过程中,点击编辑回显数据的问题修复.
  • 操作HTML网页的知识点
  • 飞搭系列 | 子事件流节点,让逻辑复用更简单!
  • 【前端】Vue 3 页面开发标准框架解析:基于实战案例的完整指南
  • 第二次线上事故