简体   繁体   English

如何使用 javascript 从表单存储数据并将其显示在新页面上?

[英]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.我需要制作一个包含 2 个输入字段的表单。 When you press submit it should take you to a new page and display the input data.当您按下提交时,它应该将您带到一个新页面并显示输入数据。

This is my html code这是我的 html 代码

<!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这是我的js代码

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.我有第二个 html 页面,名为 Success.html,我想显示表单中给出的数据。 I need to make a mock API so I tried using reqres.我需要模拟 API 所以我尝试使用 reqres。

This is my Success.html page这是我的 Success.html 页面

<!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 `` Success.html:16 Uncaught ReferenceError: request is not defined at Success.html:16:35

The line const formData = JSON.parse(request.body);该行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.在你的success.html试图引用一个名为request的变量,它没有在它包含的<script>标签的 scope 中定义 - 这就是你得到ReferenceError: request is not defined错误的原因。

This other Stackoverflow question seems similar to yours - I have linked you to an answer that I think would be helpful. This other Stackoverflow question seems similar to yours - I have linked you to an answer that I think would help. 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 .简而言之,您可以从response中提取您关心的值,然后通过查询参数传递它们以显示在您的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.按照同样的思路,您的模拟 API 用 302 状态代码和位置 header 进行响应可能是有意义的,包括指向您的成功页面的电影和评级查询参数。

You can pass along data between web pages in several ways, using JSON data { foo: 'bar' } as an example:您可以通过多种方式在 web 页之间传递数据,以 JSON data { foo: 'bar' }为例:

1. Use URL parameter: 1.使用URL参数:

  • Stringify and URL encode your JSON response (full or needed data only), and pass along via a URL parameter Stringify 和 URL 编码您的 JSON 响应(仅完整或需要的数据),并通过 URL 参数传递
  • Example: 'data=' + encodeURIComponent(JSON.stringify(data)) , resulting in data=%7B%20foo%3A%20'bar'%20%7D示例: 'data=' + encodeURIComponent(JSON.stringify(data)) ,结果为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请记住,URL 的长度是有限制的,根据浏览器的不同,从 2k 到 64k 不等

2. Use browser local storage: 2.使用浏览器本地存储:

  • The quota is browser specific, in range of 5-10MB, eg much larger than URL length配额是特定于浏览器的,在 5-10MB 范围内,例如比 URL 长度大得多
  • To set in the form page: localStorage.setItem('myFormData', JSON.stringify(data));在表单页面设置: 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)要在成功页面中阅读: let data = JSON.parse(localStorage.getItem('myFormData'); (您可能想添加一些错误处理)

3. Temporarily POST data 3.临时POST数据

  • You post the JSON data back to the server to /success您将 JSON 数据回传到服务器/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您的成功页面是通过服务器端脚本动态传送的,该脚本通过 POST 接收数据,并将其返回为 JSON 或任何其他首选格式
  • 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.您可以使用本机 JavaScript 或 jQuery 轻松更新 DOM。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何仅使用JavaScript将表单数据从一个HTML页面传递到另一HTML页面? - How do I pass form data from one HTML page to another HTML page using ONLY javascript? 如何使用JavaScript在同一页面上显示包含名字,姓氏电子邮件和密码验证的表单数据 - How do I display a form data containing first name last name email and password validations in the same page using JavaScript 使用JavaScript将数据从表单显示到另一个页面 - Display Data from a form to another page using JavaScript 如何使此“配置文件”表单本地存储数据? Javascript - How do I make this 'profile' form localy store the data? Javascript 我如何从一个页面到另一个页面获取数据,只需使用JavaScript在屏幕上简单显示 - How do i get data from a page to other page,just simply display on screen with javascript 如何使用JavaScript存储网页/网页中的数据? - How to store a web page/ data from web page using JavaScript? 如何在此 HTML 页面中存储数据并使用 JavaScript 在另一个页面中检索它 - How do I store data in this HTML page and retrieve it in another using JavaScript 在html文档中使用表单时,如何在同一页面中显示数据? - How do i display data in the same page while using a form in a html doc? 如何使用 javascript 从表单中收集数据并将其存储在变量中? - How can i collect data from form with javascript and store it in variables? 如何从第三方API提取数据并使用javascript将其显示在我的页面上? - How do I extract data from a 3rd party api and display it on my page with javascript?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM