温馨提示×

如何在不刷新页面的情况下提交form表单

小樊
81
2024-06-29 19:04:42
栏目: 编程语言

您可以使用 JavaScript 来在不刷新页面的情况下提交表单。以下是一个示例代码:

<form id="myForm">
  <input type="text" name="name" placeholder="Name">
  <input type="email" name="email" placeholder="Email">
  <button type="button" onclick="submitForm()">Submit</button>
</form>

<script>
function submitForm() {
  var form = document.getElementById("myForm");
  var formData = new FormData(form);

  fetch("your-api-endpoint", {
    method: "POST",
    body: formData
  })
  .then(response => response.json())
  .then(data => {
    console.log(data);
    // Add code here to handle the response data
  })
  .catch(error => {
    console.error(error);
    // Add code here to handle any errors
  });
}
</script>

在这个示例中,我们首先创建一个包含输入字段和提交按钮的表单。提交按钮使用 type="button",而不是默认的 type="submit",以防止表单默认的刷新行为。

当用户点击提交按钮时,submitForm() 函数会被调用。该函数首先获取表单元素,然后使用 FormData 对象将表单数据序列化。接着使用 fetch 方法向指定的 API 端点发起 POST 请求,将表单数据作为请求体发送。

最后,我们可以使用 .then() 方法处理 API 响应,并使用 .catch() 方法处理任何可能的错误。

请确保将 your-api-endpoint 替换为您实际的 API 地址。

0