I'm saving a bunch of variables, arrays, and objects with an ajax call and then loading them later. There are a lot of them. Do I have to save each property individually? Like this:
function save() {
var saveData = [
[obj1.a, obj1.b, obj1.c, obj1.d, obj1.e],
[obj2.a, obj2.b, obj2.c, obj2.d, obj2.e],
[obj3.a, obj3.b, obj3.c, obj3.d, obj3.e]
];
var xhttp = new XMLHttpRequest();
xhttp.open("POST", "./api/save", true);
xhttp.setRequestHeader('Content-type', 'application/json');
xhttp.send(JSON.stringify(saveData));
}
Or is there any shorter way? Can I JSON.stringify the individual objects and then send them? Like this:
var saveData = [
[JSON.stringify(obj1)],
[JSON.stringify(obj2)],
[JSON.stringify(obj3)]
};
RESPONSE:
Yes that is what I was looking for. I was not getting it to load correctly when I called the data back from the server, so I thought maybe you couldn't send "whole" objects like that.
For example once I load the data from the server and parse it, shouldn't I be able to access it in the same way?
var loadedData = JSON.parse(this.responseText);
console.log(loadedData[1]["b"]);
should give me the same result as:
console.log(obj2["b"]);
yes?
That brings me to the second part of the question. Loading a bunch of variables, arrays, objects... is there an easy way to do that? Like if I want to overwrite the local values with the values loaded from the server? Can I go:
obj1 = loadedData[0];
Or do I have to go through and set the properties one by one? like:
obj1[0] = loadedData[0][0];
ojb1[1] = loadedData[0][1];
etc? (or with a loop)