javascript - 我想知道如何保存用户通过表单输入的数据,以便在重新打开应用程序后重新加载数据
问题描述
我想存储用户使用表单和香草 JS 估算的数据。
因此,当我重新打开页面时,任何推送到数组的数据在登录到控制台时仍然可见。
我已经做了一些研究并理解使用 Json 是答案(我认为)。
我做了一些研究,但我发现的一切似乎都使用了 Node.js。
任何链接或代码将不胜感激。
注意:如果需要,我可以发布更多代码,发布的代码是提交表单后执行的函数。
const formEl = document.getElementById('mainForm');
const comment = document.getElementById('comment');
formEl.onsubmit = function (e) {
//Selecting the comment input on the form to pass to the
//comment waiters array.
const comment = document.getElementById('comment').value;
//Selecting the choosen index from the user food and which waiter orderd //it which waiter.
//Selects the choosen food to pass to the addFood method in the waiter //class.
const foodItemIndex = foodMain.options[foodMain.selectedIndex].value;
const foodItem = mainFood[foodItemIndex];
//Selecting the waiter to push valid informaiton to.
const waiterName = waitersEl.options[waitersEl.selectedIndex].value;
const waiter = waiters.find(({name}) => name === waiterName);
//Logic to check when submited if both feilds are true proceed.
//The statements check to see which feild values have been entered
//Then it call's the corresponding method from the waiter class and
//pushes the value to the choosen array
if (waiter && foodItem && comment) {
waiter.addFood(foodItem)
waiter.addComment(comment);
console.log(waiters);
}
else if (waiter && comment) {
waiter.addComment(comment);
console.log(waiters);
}
else if (waiter && foodItem){
waiter.addFood(foodItem)
console.log(waiters);
}
formEl.reset();
return false; // prevents redirect/refresh
};
表单提交一次后:
0: Waiter
comment: ["This form has been submitted I will now close the window and when I reopen I will not be here"]
name: "Timo"
order: [Item]
total: 14
现在当我重新打开时:
0: Waiter
comment: []
name: "Timo"
order: []
total: 0
我想要它,所以当我重新打开数据时,数据仍在数组中。
解决方案
如果您只想使用 JavaScript,则可以使用 cookie 或 LocalStorage。
LocalStorage 是一种网络存储,它允许 Javascript 网站和应用程序直接在浏览器中存储和访问数据,没有过期日期。这意味着即使在浏览器窗口关闭后,存储在浏览器中的数据也会保留。
LocalStorage 的工作方式如下:
const person = {
name: "Obaseki Nosa",
location: "Lagos",
}
window.localStorage.setItem('user', JSON.stringify(person));
要检索上面存储的用户密钥:
window.localStorage.getItem('user');
这将返回一个值为的字符串;
"{"name":"Obaseki Nosa","location":"Lagos"}"
为了获取本地存储中所有内容的值,请使用:
Object.entries(localStorage)
要使用此值,您必须将其转换回对象。
为此,我们使用JSON.parse()
将 JSON 字符串转换为 Javascript 对象的方法。
JSON.parse(window.localStorage.getItem('user'));
但是,如果您希望这是一个应用程序而不是一种作业形式,我建议您保存然后通过服务器取回数据(例如通过使用 PHP 和 MySQL 数据库)。
推荐阅读
- node.js - Google App Engine - 上传到存储桶后访问文件
- python - 带有 PostgreSQL IntegerRangeField 的 Django 保持顺序
- android - Flutter google_mobile_ads 在 Android 模拟器中工作但不在发布应用程序中
- python - 如何使用python控制手机?
- django - 如何排除 db Django 中的项目
- spring - BindingResult/Errors 没有在模型属性之后立即声明,但是没有问题,为什么?
- wpf - 如何使用用户控件中所有可用的列表视图宽度?
- c# - 对已知为原始类型的模板变量的值使用比较运算符
- javascript - 处理数组 Javascript 或 Jquery 问题的提示
- reactjs - 带有“npx create-react-app”的 IPFS-JS 导致 Webpack 错误