javascript event.preventDefault()不会阻止页面刷新,我正在使用勇敢的浏览器

w41d8nur  于 2023-03-11  发布在  Java
关注(0)|答案(2)|浏览(212)

每次我点击提交按钮,数据被添加到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){

     }
}
zbdgwd5y

zbdgwd5y1#

我并不是直接处理您的preventDefault问题,但我建议您用一个替代品来代替那个可怕的、失控的“async/await”组合!
尝试这种逻辑和可管理的替代格式来获取的东西...

fetch('http://localhost:8080/books',{

            method: "POST",

            body: JSON.stringify(bookDetails),

            headers: {"Content-Type":"application/json"}

          }).then(resp => resp.json()).then(function(data){

 // process "data" here as needed

});
mv1qrgav

mv1qrgav2#

将true添加到要在捕获阶段执行的调用中:

form.addEventListener("submit", getBooksData) {

function getBooksData(event){
    event.preventDefault()
    // ...
}, true);

有关此内容的更多阅读,请查看https://www.w3.org/TR/DOM-Level-3-Events/

相关问题