繁体   English   中英

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

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

我需要制作一个包含 2 个输入字段的表单。 当您按下提交时,它应该将您带到一个新页面并显示输入数据。

这是我的 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>

这是我的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);
    });
});

我有第二个 html 页面,名为 Success.html,我想显示表单中给出的数据。 我需要模拟 API 所以我尝试使用 reqres。

这是我的 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>

我认为这会起作用,但在按提交后出现此错误:

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

该行const formData = JSON.parse(request.body); 在你的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 help. 简而言之,您可以从response中提取您关心的值,然后通过查询参数传递它们以显示在您的success.html中。

按照同样的思路,您的模拟 API 用 302 状态代码和位置 header 进行响应可能是有意义的,包括指向您的成功页面的电影和评级查询参数。

您可以通过多种方式在 web 页之间传递数据,以 JSON data { foo: 'bar' }为例:

1.使用URL参数:

  • Stringify 和 URL 编码您的 JSON 响应(仅完整或需要的数据),并通过 URL 参数传递
  • 示例: 'data=' + encodeURIComponent(JSON.stringify(data)) ,结果为data=%7B%20foo%3A%20'bar'%20%7D
  • 请记住,URL 的长度是有限制的,根据浏览器的不同,从 2k 到 64k 不等

2.使用浏览器本地存储:

  • 配额是特定于浏览器的,在 5-10MB 范围内,例如比 URL 长度大得多
  • 在表单页面设置: localStorage.setItem('myFormData', JSON.stringify(data));
  • 要在成功页面中阅读: let data = JSON.parse(localStorage.getItem('myFormData'); (您可能想添加一些错误处理)

3.临时POST数据

  • 您将 JSON 数据回传到服务器/success
  • 您的成功页面是通过服务器端脚本动态传送的,该脚本通过 POST 接收数据,并将其返回为 JSON 或任何其他首选格式
  • 额外的工作,所以不推荐

列出之后,为什么不在表单页面本身中显示内容呢? 您可以使用本机 JavaScript 或 jQuery 轻松更新 DOM。

暂无
暂无

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

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