我在SO上看到过类似这个问题的帖子,但我还没能解决我的问题。我想从表单提交数据,然后重定向到一个新的html页面。数据提交,但我没有被重定向到newPage.html。
我认为这与表单中的操作字段有关,因为当我删除/修改action=“/submit_name”
时,它根本不起作用。
这就是我到目前为止所做的:
<!DOCTYPE html>
<html>
<body>
<script>
function submit() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
window.location.href = "http://localhost:8080/newPage.html";
}
};
xhttp.open("POST", "/submit_name", true);
var form_data = new FormData(document.getElementById("myForm"));
xhttp.send(form_data);
}
</script>
<H1> Who are you? </H1>
<form id="myForm" action="/submit_name" method="post" onsubmit="return submit();">
<label for="name"> Name:</label>
<input type="text" id="name" name="user_name">
<input type="submit" value="Submit">
</body>
</html>
有人能帮我吗?
发布于 2020-11-18 12:36:26
您的事件侦听器未正确绑定。
使用属性绑定事件侦听器充其量也是参差不齐的。找到元素并使用addEventListener
。我稍微修改了您的XHR请求,使其记录堆栈片段,但不需要进行任何修改。只要避免使用onsubmit=""
和它的朋友即可。
document.querySelector('form').addEventListener('submit', function(event) {
event.preventDefault();
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
console.log("Success");
window.location.href = "http://localhost:8080/newPage.html";
}
};
xhttp.open("POST", "/submit_name", true);
var form_data = new FormData(document.getElementById("myForm"));
xhttp.send(form_data);
})
<body>
<H1> Who are you? </H1>
<form id="myForm" action="/submit_name" method="post">
<label for="name"> Name:</label>
<input type="text" id="name" name="user_name">
<input type="submit" value="Submit">
</form>
</body>
https://stackoverflow.com/questions/64862037
复制相似问题