简体   繁体   中英

How prevent reload after post request?

I am trying to make a post request to the server and do something with the response. Things seem to work on the server-side. The problem is that the page reloads upon completion of the response and I cannot do anything with the response.

The common suggestions are using button or preventDefault . These suggestions do not solve the problem: as you can see below, the input type is button (not submit ) and preventDefault() on the event does not work.

Does anyone have an idea about what I am missing?

 <form id="modelCodeForm">
    <label for="codehere"></label>
    <div id="modelAreaDiv">
      <textarea id="modelArea" cols="60" rows="20">
stuff
      </textarea>
      <br>
      <input id="submitUserModel" type="button" value="run on server">
  </div>
  </form>
function initializeUserModel(){
  let model = document.getElementById("modelArea").value;
  fetch('http://localhost:8080/', {
      method: 'post',
      headers: {'Content-Type': 'text/plain'},
      body: model
    })
      .then(response => response.json())
      .then(data => {
        console.log(data);
      }).then(console.log("received!"))     
}  

I got to the bottom of this. It turns out that the problem was due to VS Live Server which was detecting a change in the folder and hot-loading the app. The change was due to the backend, in the same folder, saving a log. Really silly thing to miss...

If you want to trigger your function when the form is submitted then you can use the "onsubmit" event listener available on HTML forms.

So you would do onsubmit="initializeUserModel(event)" . You pass it the event object so you can call event.preventDefault() in the function and stop the page from reloading.

Change your input to type="submit" (or make it a button of type="submit") or the form submission won't be triggered.

    <form id="modelCodeForm" onsubmit="initializeUserModel(event)">
      <label for="codehere"></label>
      <div id="modelAreaDiv">
        <textarea id="modelArea" cols="60" rows="20">Stuff</textarea>
        <br />
        <input id="submitUserModel" type="submit" value="run on server" />
      </div>
    </form>
  function initializeUserModel(event) {
    event.preventDefault();
    let model = document.getElementById("modelArea").value;
    fetch("http://localhost:8080/", {
      method: "post",
      headers: { "Content-Type": "text/plain" },
      body: model,
    })
      .then((response) => response.json())
      .then((data) => {
        console.log(data);
      })
      .then(console.log("received!"));
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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