如何在客户端存储临时数据,然后将其发送到服务器

我需要临时在客户端存储数据,以允许用户添加,编辑或删除项目,而无需为每个操作查询服务器; 就在用户完成添加项目并单击“ 添加”按钮时,列表将被发送到服务器以永久保存。

此图像描述了我想要实现的目标。 我知道我必须在JavaScript中使用数组,但我不知道如何创建一个用于存储对象(在本例中, Detail包含:id,price和description)。

我希望你能帮助我。 提前致谢。 PS:我正在使用JSP …对不起我的英语

当然,因为它是一个表,所以有一个对象数组是有意义的。 请注意,对象由大括号括起,数组由括号括起:

var myArray = []; // Initialize empty array var myObject = {}; // Initialize empty object 

这应该完成你需要的:

 // 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); 

这与此相同:

 // Initialize array var table = []; // Create object and add the object to the end of the array table.push({ id: '22', price: '$222', description: 'Foo' }); 

您现在可以访问如下属性:table [0] .id; //’22’

在现代浏览器中,如果您希望数据在会话中保持不变(如cookie),则可以使用sessionStorage或localStorage对象。

当您想要将数据发送到服务器时,您将通过网络发送表的JSON版本:

 var data = JSON.stringify(table); 

您可以使用对象文字非常轻松地创建自定义Detail对象的数组:

 var details = []; details.push({id:'abc1234', price:999.99, description:'Tesla Roadster'}); details.push({id:'xyz5678', price:129.99, description:'Land Rover'}); 

然后,当用户单击“添加”时,您可以将数据发布到服务器。

对于JSON来说听起来不错。