javascript 如何在客户端存储临时数据,然后将其发送到服务器
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4329860/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to store temporary data at the client-side and then send it to the server
提问by David Calhoun
I need to store data temporarily at the client-side to allow users to add, edit or delete items without having to query the server for each of these actions; just when the user finishes adding items and clicks on the Addbutton, the list is sent to the server to be saved permanently.
我需要在客户端临时存储数据,以允许用户添加、编辑或删除项目,而无需为这些操作中的每一个查询服务器;当用户完成添加项目并单击“添加”按钮时,列表将发送到服务器以永久保存。
This imagedescribes what I want to achieve. I know I have to use arrays in JavaScript, but I don't know how to create one to store objects (in this case Detailwhich contains :id, price and description).
这张图片描述了我想要实现的目标。我知道我必须在 JavaScript 中使用数组,但我不知道如何创建一个数组来存储对象(在这种情况下,包含 :id、price 和 description 的Detail)。
I hope you can help me out. Thanks in advance. PS: I'm using JSP and... sorry for my English
我希望你能帮助我。提前致谢。PS:我正在使用 JSP 和...对不起我的英语
回答by David Calhoun
Sure, since it's a table it makes sense to have an array of objects. Note that an object is surrounded by curly braces and an array is surrounded by brackets:
当然,因为它是一个表,所以有一个对象数组是有意义的。请注意,对象用大括号括起来,数组用方括号括起来:
var myArray = []; // Initialize empty array
var myObject = {}; // Initialize empty object
This should accomplish what you need:
这应该可以完成您的需要:
// Initialize variables
var newEntry, table = [];
// Create a new object
newEntry = {
id: '',
price: '',
description: ''
};
// Add the object to the end of the array
table.push(newEntry);
Which is the same as this:
这与此相同:
// Initialize array
var table = [];
// Create object and add the object to the end of the array
table.push({
id: '22',
price: '2',
description: 'Foo'
});
You can now access properties like this: table[0].id; // '22'
您现在可以访问这样的属性: table[0].id; // '22'
On modern browsers, if you want the data to persist across sessions (like cookies) you could use the sessionStorage or localStorage objects.
在现代浏览器上,如果您希望数据跨会话(如 cookie)保持不变,您可以使用 sessionStorage 或 localStorage 对象。
When you want to send the data to the server, you'll send a JSON version of the table across the wire:
当您想将数据发送到服务器时,您将通过网络发送表的 JSON 版本:
var data = JSON.stringify(table);
回答by Rob Sobers
You can create an Array of your custom Detail objects pretty easily with object literals:
您可以使用对象字面量轻松创建自定义 Detail 对象的数组:
var details = [];
details.push({id:'abc1234', price:999.99, description:'Tesla Roadster'});
details.push({id:'xyz5678', price:129.99, description:'Land Rover'});
Then you can post your data to the server when the user clicks "Add."
然后,当用户单击“添加”时,您可以将数据发布到服务器。

