1811a-zsgc 中文文档教程
后台
const express=require('express');
const app=express();
const fs=require('fs');
app.use(express.static('public',{
index:'index.html'
}));
app.use(express.json());
// 页面
app.post('/api/list',(req,res)=>{
let data=JSON.parse(fs.readFileSync('mock/list.json'));
res.send(data)
});
// 编辑
app.post('/api/compile',(req,res)=>{
let {name,city,title,id}=req.body
let data=JSON.parse(fs.readFileSync('mock/list.json'));
let o=data.find(item=>item.id===req.body.id);
// console.log(o,req.body);
Object.assign(o,req.body);
fs.writeFileSync('mock/list.json',JSON.stringify(data))
res.send({code:1})
})
app.listen(8080,()=>console.log('8080启动了!'));
// 删除
app.post('/api/del',(req,res)=>{
let { id }=req.body;
let data=JSON.parse(fs.readFileSync('mock/list.json'));
data=data.filter(item=>item.id!==id);
fs.writeFileSync('mock/list.json',JSON.stringify(data));
res.send({code:1})
})
前台
let wrap=document.querySelector('.wrap'),
ullist=document.querySelector('.ullist'),
mask=document.querySelector('.mask'),
city=document.querySelector('.city'),
name=document.querySelector('.name'),
title=document.querySelector('.title'),
ID,
ollist=document.querySelector('.ollist');
// 列表
rander()
function rander(){
axios.post('/api/list').then(result=>{
console.log(result.data);
ollist.innerHTML=result.data.map(item=>{
return`<li my-id='${item.id}'>
<span>></span>
<span>${item.name}</span>
<span>${item.city}</span>
<span>${item.title}</span>
<span>
<button class="compile" my-id='${item.id}'>编辑</button>
<button class="add" my-id='${item.id}'>添加食品</button>
<button class="del" my-id='${item.id}'>删除</button>
</span>
</li>`
}).join('')
})
}
// 编辑
ollist.addEventListener('click',e=>{
let tar=e.target;
if(tar.className==='compile'){
mask.style.display='block';
ID=tar.getAttribute('my-id');
}
})
mask.addEventListener('click',e=>{
let tar=e.target;
if(tar.className==='no'){
mask.style.display='none'
}
if(tar.className==='ok'){
mask.style.display='none';
// let id=tar.getAttribute('my-id')
console.log(ID);
axios.post('/api/compile',{
name:name.value,
city:city.value,
title:title.value,
id:ID
}).then(result=>{
result.data.code&&rander()
})
}
})
// 删除
ollist.addEventListener('click',e=>{
let tar=e.target;
if(tar.className==='del'){
ID=tar.getAttribute('my-id')
console.log(ID);
axios.post('/api/del',{id:ID}).then(result=>{
result.data.code&&rander()
})
}
})
// 增加
ollist.addEventListener('click',e=>{
let tar=e.target;
if(tar.className==='add'){
ID=tar.getAttribute('my-id')
console.log(ID);
axios.post('/api/del',{id:ID}).then(result=>{
result.data.code&&rander()
})
}
})
更多