ajax方式实现图书案例增删改查
let tbody = document.querySelector('tbody')
let btnadd = document.querySelector('.btnadd')
let bookname = document.querySelector('[name="bookname"]')
let author = document.querySelector('[name="author"]')
let publisher = document.querySelector('[name="publisher"]')
let editbookname = document.querySelector('#bookname')
let editauthor = document.querySelector('#author')
let editpublisher = document.querySelector('#publisher')
let btnConfirm = document.querySelector('.btnConfirm')
function init() {
axios({
url: 'http://www.itcbc.com:3006/api/getbooks',
method: 'GET'
}).then(res => {
let str = ''
res.data.data.forEach(function (value, index) {
str += `
<tr>
<th scope="row">${index + 1}</th>
<td>${value.bookname}</td>
<td>${value.author}</td>
<td>${value.publisher}</td>
<td>
<button type="button" class="btn btn-link btn-sm btndel" data-id='${value.id}'>删除</button>
<button type="button" class="btn btn-link btn-sm btnedit" data-id='${value.id}' data-bookname='${value.bookname}' data-author='${value.author}' data-publisher='${value.publisher}'>编辑</button>
</td>
</tr>
`
});
tbody.innerHTML = str
})
}
init()
btnadd.addEventListener('click', function (e) {
e.preventDefault()
axios({
url: 'http://www.itcbc.com:3006/api/addbook',
method: 'POST',
data: {
bookname: bookname.value,
author: author.value,
publisher: publisher.value
}
}).then(res => {
bookname.value = author.value = publisher.value = ''
if (res.data.status == 0) {
alert(res.data.message)
init()
} else {
alert('添加失败')
}
})
})
tbody.addEventListener('click', function (e) {
if (e.target.classList.contains('btndel')) {
if (confirm('是否要删除')) {
let id = e.target.dataset.id
axios({
url: 'http://www.itcbc.com:3006/api/delbook',
method: 'DELETE',
params: { id }
}).then(res => {
if (res.data.status == 0) {
alert(res.data.message)
init()
} else {
alert('删除失败')
}
})
}
}
})
let id
tbody.addEventListener('click', function (e) {
if (e.target.classList.contains('btnedit')) {
let data = e.target.dataset
id = data.id
$('#myModal').modal('show')
editbookname.value = data.bookname
editauthor.value = data.author
editpublisher.value = data.publisher
}
})
btnConfirm.addEventListener('click', function () {
let data = {
id: id,
bookname: editbookname.value,
author: editauthor.value,
publisher: editpublisher.value
}
axios({
url: 'http://www.itcbc.com:3006/api/updatebook',
method: 'PUT',
data,
}).then(res => {
if (res.data.status == 0) {
alert(res.data.message)
$('#myModal').modal('hide')
init()
} else {
alert('修改失败')
}
})
})