简体   繁体   English

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

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

I've seen posts similar to this problem on SO, but I've not been able to solve my problem yet.我在 SO 上看到过类似这个问题的帖子,但我还没有解决我的问题。 I want to submit data from a form and then redirect to a new html page.我想从表单提交数据,然后重定向到新的 html 页面。 The data submits, but I'm not redirected to newPage.html.数据提交,但我没有重定向到 newPage.html。

I think this has something to do with my action field in the form since when I remove/modify action=“/submit_name” , it doesn't work at all.我认为这与我在表单中的 action 字段有关,因为当我删除/修改action=“/submit_name” ,它根本不起作用。

This is what I've done so far:这是我到目前为止所做的:

<!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>

Can someone help me?有人能帮我吗?

Your event listener isn't binding properly.您的事件侦听器未正确绑定。

Using attributes for binding event listeners is spotty at best.使用属性来绑定事件侦听器充其量是参差不齐的。 Find the element and use addEventListener .找到元素并使用addEventListener I modified your XHR request slightly to make it log for stack snippets, but no modification is needed.我稍微修改了您的 XHR 请求,使其记录堆栈片段,但不需要修改。 Just avoid using onsubmit="" and it's friends.只是避免使用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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM