Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
258 views
in Technique[技术] by (71.8m points)

javascript - 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.

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).

I hope you can help me out. Thanks in advance. PS: I'm using JSP and... sorry for my English

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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: '$222',
  description: 'Foo'
});

You can now access properties like this: 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.

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...