Key value datastructure in JavaScript
I have a google map where user places markers at various locations. I show a jquery dialog on click event which has a form, where user will fill other details pertaining to the marker. Now i need to make this data persist:
1] I need to store the markers ( along with the details ) to a hidden field of a form, so my server can parse it and populate the database. Something on the line of:
markerData = JSON.stringify($('#dialog' + markerId).serializeObject()); // the form
.. add the markerData with key as markerId to a global javascript variable ..
$('#markersList').val( JSON.stringify("the global var"));
Note:
$('#dialog' + markerId)
will uniquely identify the markers dialog(which has the form)
2] I need to retrieve the values from the database and form the string that will be placed in the hidden field. This is required for the edit/view page.
Basically i need a datastructure(key/value) in javascript where markerId is the key and the form elements are the values, AND i need a way to convert all the values in a format parsable by server (via hidden开发者_运维技巧 field) and vice versa.
What about:
var keyValuePairs = [{ "key1": "value1" }, { "keyN": "valueN" }];
alert(keyValuePairs["key1"]);
Or just:
var keyValuePairs = {};
keyValuePairs["key1"] = "value1";
keyValueParis["keyN"] = "value2";
alert(keyValuePairs["key1"]);
UPDATE: If you want to post this associative array as JSON in a hidden field, just stringify the array with the JSON library of your choice and set JSON text to the whole hidden field.
All objects in javascript are key/value pairs. What else do you need? You can have it like that:
Define a variable
var userInput = {}
as soon as for given markerId
you have formElements
specified, just do
userInput[markerId] = formElements
It is the same as if you'd have a concrete Id when writing your code (say Id1
) and write
userInput.Id1 = formElements
So after that you have userInput
object with property names equal to your ids (keys), and values equal to user defined form elements - exactly what you need, right?
精彩评论