Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am creating a Flask app, and I'm just starting trying to mix flask and javascript, my script is suuuuper easy:

<!DOCTYPE html>
<html>
<body>
<button id="mybtn">click me to start</button>
<p>click the button to start the count</p>
<p id="demo"></p>

<script>
document.getElementById("mybtn").addEventListener("click", startTimer);
var t = 0;

function startTimer(){
  var myVar = setInterval(myTimer, 5000);
}


function myTimer() {
  t = t + 1;  
  //var d = new Date();
  //var t = d.toLocaleTimeString();
  document.getElementById("demo").innerHTML = t;
}
</script>

</body>
</html>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
115 views
Welcome To Ask or Share your Answers For Others

1 Answer

This is not because of "merging" flask with js, but how the form tag in HTML works.

When a form is submitted in HTML, with <input type="submit">, the action page of the form is loaded. Since it's the same page here, the page will be reloaded on submit, which means all javascript in the browser is reset (in a way).

I am assuming you are trying to submit the form without reloading the page, it is possible with async requests and you can do it by adding the following js. But note that the page won't be reloaded, so any HTML that you might be generating on the server(flask side) will not be updated (but form will be submitted in the background).

document.addEventListener("submit", (e) => {
  // Store reference to form to make later code easier to read
  const form = e.target;

  // Post data using the Fetch API
  fetch(form.action, {
    method: form.method,
    body: new FormData(form),
  });

  // Prevent the default form submit
  e.preventDefault();
});

You can see more info regarding this and how to extend here: https://pqina.nl/blog/async-form-posts-with-a-couple-lines-of-vanilla-javascript/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...