IndexedDB 如何在本地存储中存储表单数据?

c3frrgcw  于 2023-02-14  发布在  IndexedDB
关注(0)|答案(2)|浏览(271)

我正在实现一个表单提交过程,但是我没有使用任何数据库(后端)。我想在客户端或浏览器存储表单数据。所以我打算使用本地存储。

<html>

<head>
    <title>Bootstrap Example</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>

</head>

<body>
    <div class="container">      
        <div class=" row ">
            <div class="col-md-6">
                <form  method="post">
                    <div class="form-group">
                        <label for="usr">Name</label>
                        <input type="text" class="form-control" id="usr" placeholder="Enter your name" required>
                    </div>
                    <div class="form-group">
                        <label for="phone">Phone</label>
                        <input type="text" class="form-control" id="phone" placeholder="Enter your phone" required>
                    </div>
                    <div class="form-group">
                        <label for="email">Email</label>
                        <input type="email" class="form-control" id="email" placeholder="Enter your email" required>
                    </div>
                    <div class="form-group">
                        <label for="pwd">Password</label>
                        <input type="password" class="form-control" id="pwd" required>
                    </div>
                    <button type="submit " class="btn btn-success" formaction="../BootStrapTemplate/detail.html">Submit</button>

                </form>
            </div>
        </div>
      
    </div>
</body>

</html>

我想在点击提交按钮后存储数据。它也将导航到另一个页面(detail.html页面),在detail.html中我将显示所有信息。
一些额外的信息,我必须显示在详细页面,ID和时间。

我想根据ID存储数据(意味着第一次保存的数据id值应为1,第二次保存的数据值应为2)
我将使用本地存储第一次。所以我不知道这么多关于本地存储。ID应该是唯一的每条记录。据我说,这是一个更好的主意。如果有人有好主意存储在客户端的数据,请让我知道。
我已经看到了一个链接,但我不能做多个输入字段,我也想形成的键,值JSON.

j9per5c4

j9per5c41#

有一些插件可用,但如果你不想使用. Plugin-to-Save-Form-Fields-Values-To-localStorage
你可以用这个。

window.localStorage-存储没有过期日期的数据
window.sessionStorage-存储一个会话的数据(关闭浏览器选项卡时数据丢失)*
注意:- * 在使用Web存储之前,请检查浏览器是否支持localStorage和sessionStorage*。

储存

localStorage.setItem("lastname", "Smith");

要检索

document.getElementById("result").innerHTML = localStorage.getItem("lastname");
sxpgvts3

sxpgvts32#

这是一个使用JavaScript的多步骤过程。修改您的页面以执行以下操作(按顺序,全部使用JavaScript)

  • 表单提交事件-防止默认值(将停止页面向服务器发送数据)
  • 表格数据的生成对象
  • 使用JSON.stringify()将表单数据JS对象转换为JSON
  • 将JSON字符串设置为localStorage键,例如localStorage.myKey = myJSON;
  • 将页面重定向到detail.html
  • 访问本地存储并解码JSON

相关问题