一、json-server的安装
npm install -g json-server
二、db.json
{
"books": [
{
"id": 1,
"name": "三体",
"price": 23.5
},
{
"id": 2,
"name": "流浪地球",
"price": 100
},
{
"name": "某书",
"price": "23.5",
"id": 3
},
{
"name": "某书",
"price": "23.5",
"id": 4
},
{
"name": "某书",
"price": "23.5",
"id": 5
},
{
"name": "某书",
"price": "23.5",
"id": 6
},
{
"name": "某书",
"price": "23.5",
"id": 7
},
{
"name": "某书",
"price": "23.5",
"id": 8
},
{
"name": "某书",
"price": "23.5",
"id": 9
}
]
}
三、index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
#books table{
width: 600px;
border: 1px solid blue;
border-collapse: collapse;
}
#books th,#books td{
border: 1px solid blue;
}
</style>
</head>
<body>
<form id="addbook" action="#">
<input type="text" name="bname" value="某书">
<input type="number" name="price" step="0.5" min="0" value="23.5">
<button>添加</button>
</form>
<div id="books">
</div>
<script>
let url="http://localhost:3000/books"
let id=1;
let data=[]
//[{id:id++,name:'三体',price:234.50},{id:id++,name:'流浪地球',price:34.50}];
let books=document.querySelector('#books')
//添加表单的提交方法
document.querySelector('#addbook').addEventListener('submit',function (event) {
let book={name:this.bname.value,price:this.price.value};
fetch(url,
{
method:"POST",body:JSON.stringify(book),
headers:{"Content-Type":"application/json"}
})
.then(function (res) {
return res.json()
})
.then(function (book) {
data.push(book)
render()
event.preventDefault()
})
})
function render(){
books.innerHTML=""
var table=document.createElement('table')
data.forEach(function (book) {
let tr=document.createElement('tr');
tr.appendChild(document.createElement('td')).innerText=book.id
tr.appendChild(document.createElement('td')).innerText=book.name
tr.appendChild(document.createElement('td')).innerText=book.price
//加一个button
let btn=document.createElement("button")
btn.innerText="删除"
tr.appendChild(document.createElement('td')).appendChild(btn)
//给删除按钮添加事件监听
btn.addEventListener('click',function () {
let index=data.findIndex(function (bk) {
return bk.id==book.id
})
data.splice(index,1)
render()
})
table.appendChild(tr)
})
books.appendChild(table)
}
window.onload=function(){
fetch(url,{method:"GET"})
.then(function (res) {
return res.json();
})
.then(function (books) {
data=books
render()
})
}
</script>
</body>
</html>