所以,我只是想提交一个表单,该表单向 json-server 发出 POST 请求,然后将其显示到页面中。我不想每次提交表单都刷新页面,所以我在提交事件的第一行添加了
event.preventDefault()
。 POST 请求成功,表单中的所有数据都发布到我的 json-server 中,但由于某种原因,页面总是在我提交时刷新。
这是有问题的代码块:
function monsterSubmit() {
const monsterForm = document.getElementById("monster-form");
monsterForm.addEventListener("submit", event => {
event.preventDefault();
const monsterObj = {
name: event.target[0].value,
age: event.target[1].value,
description: event.target[2].value
}
fetch("http://localhost:3000/monsters", {
method: "POST",
headers: {
"Content-Type": "application/json",
Accept: "application/json"
},
body: JSON.stringify(monsterObj)
})
.then(res => res.json())
.then(monster => console.log(monster))
.catch(err => console.log(err))
})
}
我知道问题出在 POST 请求上,因为当我将其注释掉、添加
console.log("form submitted")
并提交表单时,页面不会刷新并且我看到消息已发布到控制台,但是当我将其放回,页面在提交时刷新。知道我做错了什么吗?
可能是表单上有另一个事件侦听器导致页面刷新。为确保只调用 monsterSubmit 函数,您可以尝试在函数末尾添加 return false,如下所示:
function monsterSubmit() {
const monsterForm = document.getElementById("monster-form");
monsterForm.addEventListener("submit", event => {
event.preventDefault();
const monsterObj = {
name: event.target[0].value,
age: event.target[1].value,
description: event.target[2].value
}
fetch("http://localhost:3000/monsters", {
method: "POST",
headers: {
"Content-Type": "application/json",
Accept: "application/json"
},
body: JSON.stringify(monsterObj)
})
.then(res => res.json())
.then(monster => console.log(monster))
.catch(err => console.log(err))
});
return false;
}