添加新图书
添加
Id书名作者出版社操作
$(function () {
getBooks()
function getBooks() {
// 每次渲染要进行清除
$('#tb').empty()
//获取图书、
$.ajax({
type: 'get',
url: 'http://www.liulongbin.top:3006/api/getbooks',
success: function (res) {
console.log(res);
// 对图书data进行遍历
res.data.forEach(function (item) {
// 使用模板字符串进行添加元素
var tr = `
${item.id}${item.bookname}${item.author}${item.publisher} 删除`
// 将新建元素添加到tbody中
$('#tb').append(tr)
})
}
})
}
// 添加图书
$('#btnAdd').click(function () {
var bookname = $('#iptBookname').val().trim()
var author = $('#iptAuthor').val().trim()
var publisher = $('#iptPublisher').val().trim()
if (bookname.length <= 0 || author.length <= 0 || publisher.length <= 0) {
return alert('信息不完整!')
}
$.ajax({
type: 'POST',
url: 'http://www.liulongbin.top:3006/api/addbook',
data: {
bookname: bookname,
author: author,
publisher: publisher,
},
success: function (res) {
if (res.status !== 201) {
return alert('添加图书失败!')
}
$('#iptBookname').val('')
$('#iptAuthor').val('')
$('#iptPublisher').val('')
// 重新渲染
getBooks()
}
})
})
$('#iptPublisher').keyup(function (e) {
if (e.keyCode == 13) {
$('.addbook').click()
}
})
// 删除图书
// 给删除按钮添加事件委托
$('#tb').on('click', '.del', function () {
// 获取当前对象的 id
var ID = $(this).attr('data-id')
// 询问用户是否确定删除
var result = confirm('确认删除吗')
// 如果确定直接删除对象
if (result) {
$.ajax({
type: 'get',
url: 'http://liulongbin.top:3006/api/delbook',
data: { id: ID },
success: function (res) {
console.log(res);
if (res.status != 200) {
return alert('删除失败!')
}
// 删除之后重新渲染页面
getBooks()
}
})
}
})
})
一键复制
编辑
Web IDE
原始数据
按行查看
历史