如何在客户端存储临时数据,然后将其发送到服务器 [英] How to store temporary data at the client-side and then send it to the server
问题描述
我需要在客户端临时存储数据,以允许用户添加,编辑或删除项目,而无需为每个操作查询服务器;当用户完成添加项目并单击添加按钮时,列表将被发送到服务器以永久保存。
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 Add button, the list is sent to the server to be saved permanently.
此< a href =http://img574.imageshack.us/i/details01.png/ =noreferrer>图像描述了我想要实现的目标。
我知道我必须在JavaScript中使用数组,但我不知道如何创建一个存储对象(在这种情况下详细信息包含:id,price和description)。
This image describes 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 Detail which contains :id, price and description).
我希望你能帮助我。
提前致谢。
PS:我正在使用JSP而且...对不起我的英语
I hope you can help me out. Thanks in advance. PS: I'm using JSP and... sorry for my English
推荐答案
当然,因为它是一张桌子拥有一个对象数组是有意义的。请注意,对象用大括号括起来,数组用括号括起来:
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);
与此相同:
// 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'
You can now access properties like this: table[0].id; // '22'
在现代浏览器中,如果您希望数据在会话中保持不变(如cookie),您可以使用sessionStorage或localStorage对象。
On modern browsers, if you want the data to persist across sessions (like cookies) you could use the sessionStorage or localStorage objects.
当您想要将数据发送到服务器时,您将通过网络发送该表的JSON版本:
When you want to send the data to the server, you'll send a JSON version of the table across the wire:
var data = JSON.stringify(table);
这篇关于如何在客户端存储临时数据,然后将其发送到服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!