How to store temporary data at the client-side and then send it to the server

后端 未结 3 2009
别跟我提以往
别跟我提以往 2020-12-13 16:45

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 u

相关标签:
3条回答
  • 2020-12-13 17:08

    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);
    
    0 讨论(0)
  • 2020-12-13 17:18

    Sounds like a good job for JSON.

    0 讨论(0)
  • 2020-12-13 17:20

    You can create an Array of your custom Detail objects pretty easily with object literals:

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

    0 讨论(0)
提交回复
热议问题