<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<button class="a">text</button>
<form action=""><input type="text" name="name"><input type="text" name="price">
<button>add a book</button>
</form>
<table>
<tbody></tbody>
</table>
<script>
let tbody = document.querySelector('tbody')
document.querySelector('form').addEventListener('submit',function (event){
let name=document.querySelector('input[name="name"]').value
let price=document.querySelector('input[name="price"]').value
let book={name:name,price:price} //json数据
let xhr= new XMLHttpRequest();
xhr.onreadystatechange=function (){
if (xhr.readyState==4){
if (xhr.status==200){
alert(xhr.responseText)
}
}
}
xhr.open("POST","http://localhost:9000/books")
xhr.setRequestHeader("Content-Type","application/json")
xhr.send(JSON.stringify(book))
event.preventDefault()
})
function createTable(txt){
tbody.innerHTML='' //先清空在添加
let books = JSON.parse(txt) // 得到的数据变成json
for (let i = 0; i < books.length; i++) {
let tr = document.createElement("tr") //创建标签
let idTb = document.createElement("tb")
let nameTb = document.createElement("tb")
let priceTb = document.createElement("tb")
idTb.innerHTML=books[i].id
nameTb.innerHTML = books[i].name
priceTb.innerHTML = books[i].price
tr.appendChild(idTb)
tr.appendChild(nameTb)
tr.appendChild(priceTb)
tbody.appendChild(tr)
}
}
document.querySelector(".a").addEventListener('click',function(){
let xhr = new XMLHttpRequest();
xhr.onreadystatechange=function (){
if (xhr.readyState==4){
if (xhr.status==200){
createTable(xhr.responseText) //进行回调就执行createTable方法
}
}
}
xhr.open("GET","http://localhost:9000/books")
xhr.send()
})
</script>
</body>
</html>
代码解答;
innerHTML 中间的元素
eg:h1.innerHTML=“内容” :把内容写入
console.log(h1) :控制器输出h1
let str = Json.stringify(books) :把js对象数据变成文本 赋值 到str里
let books = Json.stringify(txt) : 把文本数据变成js对象 赋值到books里
document.querySelector("#e") : 获取id=e的元素
result.appendChild(h1) : 把h1当成儿子交给result 写在result盒子里
xhr. open("GET","网址") : xhr连接后端
button.onlick = : 用户做的事件
xhr.onreadystaechange = function(){} : 数据返回时做的 不能放在xhr.send()后面这样会变成先监听
在执行就晚了就不会返回改方法;