如何侦听表单操作 HTTP 请求完成情况?

问题描述 投票:0回答:1

我有这个表格:

<form action="/my-url" method="GET">
  <button type="submit">submit</button>
</form>

我想知道HTTP请求何时完成。这可能吗?有什么活动我可以听吗?

javascript html events
1个回答
0
投票

要处理单击提交按钮并收到响应时的事件,您可以使用 JavaScript 的 fetch API 或 XMLHttpRequest 对象发出异步 HTTP 请求。然后,您可以将事件侦听器附加到提交按钮以捕获单击事件并处理响应。 以下是使用 fetch API 的示例:

    <!DOCTYPE html>
    <html>
    <head>
      <title>Submit Button Event</title>
    </head>
    <body>
    
    <form action="#" method="GET">
      <button id="submitButton" type="button">submit</button>
    </form>
    <button >Submit</button>
    
    <script>
    document.getElementById("submitButton").addEventListener("click", function() {
  fetch("http://your-server-endpoint", {
    method: "GET",
    headers: {
      "Content-Type": "application/json"
    }
  })
  .then(response => {
    if (!response.ok) {
      throw new Error("Network response was not ok");
    }
    return response.json();
  })
  .then(data => {
    // Handle the response data
    console.log("Response received:", data);
    // You can add your logic here to handle the response
  })
  .catch(error => {
    console.error("There was a problem with the fetch operation:", error);
  });
});
    </script>
    
    </body>
    </html>

你也可以使用JQuery

© www.soinside.com 2019 - 2024. All rights reserved.