在JavaScript/HTML中,未从活动服务器收到任何响应
我在做一个学术项目,需要从网页表单中获取两个字符串输入,使用POST请求把它们发送到服务器,然后根据服务器的响应显示一条消息。我已经测试了一段时间了,但无论怎样提交,提交后都没有弹出任何提示框。我已经加入了输入验证,验证确实能工作并会弹出提示框;我也尝试过把所有验证都去掉的情况。若能提供一些帮助或建议,我将不胜感激。
这是我的表单,用来收集数据:
<div id="FormHome">
<h1>STAY INFORMED - JOIN OUR MAILING LIST:</h1>
<form name="mailList" action="MailingList.html" onsubmit="return validateMailList()" method="POST">
<label for="name">NAME:</label><br>
<input type="text" id="name" name="name"><br>
<label for="lname">EMAIL:</label><br>
<input type="text" id="email" name="email">
<input type="submit" value="SUBMIT">
</form>
</div>
以下是我的JavaScript:
<script>
function validateMailList() {
const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
let x = document.forms["mailList"]["name"].value;
if (x == "") {
alert("NAME MUST NOT BE BLANK ");
return false;
}
let y = document.forms["mailList"]["email"].value;
if (y == "") {
alert("EMAIL MUST NOT BE BLANK ");
return false;
}
if (!emailRegex.test(y)){
alert("EMAIL ADDRESS IS INVALID.")
}
const data = {
"name" : x,
"email" : y
}
fetch('//url', {
method: "post",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(data)
})
.then ((response) => {
if(response.status === 201){
alert("Thank you. You are now signed up for our mailing list");
return response. json();
}else if(response.status === 400){
alert("INVALID DATA WAS SENT TO THE SERVER.");
}else{
alert("Sorry, something went wrong.");
}
})
}
</script>
解决方案
当你提交表单时,onsubmit 函数会执行。它会发起一个异步的 fetch 请求,然后返回 undefined。这并不会阻止表单的正常提交行为,即提交到 MailingList.html。这会导致浏览器离开当前页面并终止它上面运行的所有JS(在达到解析 fetch 返回的Promise并调用 alert 之前就会发生)。
一个快速粗暴的修复方法是让 return false 从该函数返回。
一种更现代的方法是利用浏览器内置的验证系统,将函数拆分成更小的函数,并用 addEventListener 绑定处理程序。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Stay Informed — Join Our Mailing List</title>
<style>
h1, label, button {
text-transform: uppercase; /* Using CSS instead of raw ALL CAPS stops screen readers treating it as an abbreviation to be read out letter by letter */
}
</style>
</head>
<body>
<div id="FormHome">
<h1>Stay Informed — Join Our Mailing List</h1>
<form>
<label for="name">Name:</label><br>
<input type="text" id="name" name="name" required><br>
<label for="email">Email:</label><br>
<input type="email" id="email" name="email" required>
<button>Submit</button>
</form>
</div>
<script>
const form = document.querySelector('form');
const getFormData = () => {
const name = form.querySelector("#name").value.trim()
const email = form.querySelector("#email").value;
return { email, name };
}
const postFormData = (data) => fetch('//example.com', {
method: "post",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(data)
});
const handleResponse = (response) => {
if (response.ok) {
alert("Thank you. You are now signed up for our mailing list");
document.location.href = "MailingList.html";
} else if (response.status === 400) {
alert("Invalid data was sent to the server")
} else {
alert("Sorry, something went wrong.");
}
}
const formHandler = async (event) => {
event.preventDefault();
if (!form.checkValidity()) {
return false;
}
const data = getFormData();
const response = await postFormData(data);
handleResponse(response);
}
form.addEventListener("submit", formHandler);
</script>
</body>
</html>
它也可能避免使用 alert(),转而使用通过DOM方法添加的内联消息。
站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。