简体   繁体   中英

How do I store data from form and display it on a new page using javascript?

I need to make a form with 2 input fields. When you press submit it should take you to a new page and display the input data.

This is my html code

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Film survey</title>
    <link rel="stylesheet" href="style.css" />
  </head>
  <body>
    <form id="form" action="./Success.html">
      <h1>Movie survey</h1>
      <p>Thank you for participating in the film festival!</p>
      <p>Please fill out this short survey so we can record your feedback</p>

      <div>
        <label for="film">What film did you watch?</label>
      </div>
      <div>
        <input type="text" id="film" name="film" required />
      </div>
      <div>
        <label for="rating"
          >How would you rate the film? (1 - very bad, 5 - very good)
        </label>
      </div>
      <input type="text" id="rating" name="rating" required />
      <div><button class="submit">Submit</button></div>
    </form>
    <script src="script.js"></script>
  </body>
</html>

This is my js code

const formEl = document.querySelector("#form");

formEl.addEventListener("submit", (event) => {

  event.preventDefault();


  const formData = new FormData(formEl);


  fetch("https://reqres.in/api/form", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      film: formData.get("film"),
      rating: formData.get("rating"),
    }),
  })
    .then((response) => {

      window.location.href = "./Success.html";
    })
    .catch((error) => {

      console.error(error);
    });
});

I have a second html page called Success.html which I want to display tha data given in the form. I need to make a mock API so I tried using reqres.

This is my Success.html page

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Success</title>
    <link rel="stylesheet" href="style.css" />
  </head>
  <body>
    <h1>Thank you for your feedback!</h1>
    <p>You watched: <span id="film"></span></p>
    <p>You rated it: <span id="rating"></span></p>
    <script>
  
      const formData = JSON.parse(request.body);

      const filmEl = document.querySelector("#film");
      const ratingEl = document.querySelector("#rating");

      filmEl.textContent = formData.film;
      ratingEl.textContent = formData.rating;
    </script>
  </body>
</html>

I thought this would work but I get this error after pressing submit:

`` Success.html:16 Uncaught ReferenceError: request is not defined at Success.html:16:35

The line const formData = JSON.parse(request.body); in your success.html is trying to reference a variable named request , which isn't defined in the scope of the <script> tag that it's contained in - that's why you're getting the ReferenceError: request is not defined error.

This other Stackoverflow question seems similar to yours - I have linked you to an answer that I think would be helpful. In short, you could pull the values you care about out of your response , then pass them via query parameters to be displayed in your success.html .

Along those same lines, it might make sense for your mock API to respond with a 302 status code and location header including film and rating query parameters that points to your success page.

You can pass along data between web pages in several ways, using JSON data { foo: 'bar' } as an example:

1. Use URL parameter:

  • Stringify and URL encode your JSON response (full or needed data only), and pass along via a URL parameter
  • Example: 'data=' + encodeURIComponent(JSON.stringify(data)) , resulting in data=%7B%20foo%3A%20'bar'%20%7D
  • Keep in mind that there is a limit to URL length, varying from 2k to 64k depending on browser

2. Use browser local storage:

  • The quota is browser specific, in range of 5-10MB, eg much larger than URL length
  • To set in the form page: localStorage.setItem('myFormData', JSON.stringify(data));
  • To read in success page: let data = JSON.parse(localStorage.getItem('myFormData'); (you likely want to add some error handling)

3. Temporarily POST data

  • You post the JSON data back to the server to /success
  • Your success page is delivered dynamically via a server side script that receives the data via a POST, and regurgitates it as JSON or in any other preferred format
  • Extra work, so not recommended

Having listed that, why not show the content in the form page itself? You can easily update the DOM using native JavaScript or jQuery.

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