提交 HTML 表单数据,然后使用 XMLHttpRequest 重定向到新页面

Submitting HTML form data and then redirecting to a new page using XMLHttpRequest

我在SO上看到类似这个问题的帖子,但我还没能解决我的问题。我想从表单提交数据,然后重定向到新的 html 页面。数据提交,但我没有重定向到 newPage.html。

我认为这与我在表单中的操作字段有关,因为当我 remove/modify 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>

有人可以帮助我吗?

您的事件侦听器未正确绑定。

使用属性绑定事件侦听器充其量是参差不齐的。查找元素并使用 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>