每次我点击提交按钮,数据被添加到JSON服务器,但是页面被刷新,我不希望发生这种情况。为什么防止默认值不起作用?我怎样才能防止页面刷新?
let form = document.getElementById("addBooksForm").addEventListener("submit",getBooksData);
let tbody = document.getElementById("tbody");
let bookDetails = {};
function getBooksData(event){
event.preventDefault()
let coverUrl = document.getElementById("url").value;
let name = document.getElementById("name").value;
let author = document.getElementById("author").value;
let genre = document.getElementById("genre").value;
let edition = document.getElementById("edition").value;
let publisher = document.getElementById("publisher").value;
let price = document.getElementById("price").value;
bookDetails = {
coverUrl,
name,
author,
genre,
edition,
publisher,
price,
borrowed: false
};
addBooks(bookDetails);
fetchBooks();
}
async function addBooks(bookDetails){
try{
let res = await fetch(`http://localhost:8080/books`,{
method: "POST",
body: JSON.stringify(bookDetails),
headers: {"Content-Type":"application/json"}
});
let data = await res.json();
console.log(data)
}catch(err){
}
}
2条答案
按热度按时间zbdgwd5y1#
我并不是直接处理您的preventDefault问题,但我建议您用一个替代品来代替那个可怕的、失控的“async/await”组合!
尝试这种逻辑和可管理的替代格式来获取的东西...
mv1qrgav2#
将true添加到要在捕获阶段执行的调用中:
有关此内容的更多阅读,请查看https://www.w3.org/TR/DOM-Level-3-Events/