<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="./axios.min.js"></script>
<style>
div{
width: 200px;
border: 1px solid;
margin: 0px auto;
text-align: center;
display: none;
}
</style>
</head>
<body>
<input type="text" placeholder="请输入姓名" name="name">
<input type="text" placeholder="请输入id" name="id">
<input type="text" placeholder="请输入分数" name="score">
<button onclick="add()">提交</button>
<table cellspacing="0">
<tr>
<th>姓名</th>
<th>学号</th>
<th>分数</th>
</tr>
</table>
<div >
<p>修改学生信息</p>
<p><input type="text" readonly name="id" ></p>
<p><input type="text" name="name" id="" placeholder="修改姓名,不修改不填写"></p>
<p><input type="text" name="score" placeholder="修改分数,不修改不填写"></p>
<button class="button">提交</button>
</div>
<script>
let table = document.querySelector("table") //本题将增删改查的内容放入表格中,拿到总表格
//查
function run() {
axios.get("http://localhost:3000/list").then((res) => { //get在后端接口中一般用于获取数据
let arr = res.data; //res是object,里面有所有res属性,这里只需要获取数据
>
~~let td = document.querySelectorAll("td")
arr.sort((a, b) => a.id - b.id)
for (let i = 0; i < td.length; i++) {
td[i].parentElement.remove()~~
}
> 防止加数据之后,一直增加表格内容,每次跑run()方法,都会将之前加载的内容删掉
for (let i = 0; i < arr.length; i++) {
let tr = document.createElement("tr")
let td1 = document.createElement("td")
let td2 = document.createElement("td")
let td3 = document.createElement("td")
let button = document.createElement("button")
let button1 = document.createElement("button")
td1.innerHTML = arr[i].name;
td2.innerHTML = arr[i].id;
td3.innerHTML = arr[i].score;
button.innerHTML = "删除"
button1.innerHTML = "修改"
tr.appendChild(td1)
tr.appendChild(td2)
tr.appendChild(td3)
tr.appendChild(button)
tr.appendChild(button1)
table.appendChild(tr)
//删除
button.onclick = function () {
axios.delete(`http://localhost:3000/list/${arr[i].id}`).then((value) => { //delete在后端用于删除,因为id是唯一的。所以获取到id就可以删除这个对象并且一直在循环中进行操作,可以直接拿到准确的删除对象
run()
})
}
//修改
button1.onclick=function(){
document.querySelector("div").style.display="block"//前面创建了一个隐藏盒子,点击事件被触发,盒子展现
document.querySelector("p>input[name=id]").value=arr[i].id
document.querySelector("p>input[name=name]").value=arr[i].name
document.querySelector("p>input[name=score]").value=arr[i].score
//提交
document.querySelector(".button").onclick=function(){
axios.put(`http://localhost:3000/list/${arr[i].id}`,{
"name":document.querySelector("p>input[name=name]").value,
"score":document.querySelector("p>input[name=score]").value
}).then((value) => {
document.querySelector("div").style.display="none"
run()
})
}
}
}
})
}
//增
window.onload = run();
function add() {
let stu = {}
stu.id = parseInt(document.querySelector("input[name=id]").value);
stu.name = document.querySelector("input[name=name]").value;
stu.score = document.querySelector("input[name=score]").value;
console.log(stu);
axios.post("http://localhost:3000/list", stu)
.then(a => {
run()
})
}
</script>
</body>
</html>
axios的增删改查
最新推荐文章于 2024-05-26 17:08:16 发布