I have the following code
$.post(
"/factory/set",{
key : value
},
function(response) {
});
}, "json"
);
where
key = "foo"
value = "bar"
but the server always gets "key" and "bar", is there a way to set the key as variable, not string?
Object keys can be dynamically assigned in ES6 by placing an expression in square brackets. Syntax: var key="your_choice"; var object = {}; object[key] = "your_choice"; console. log(object);
JSON objects are written in key/value pairs. JSON objects are surrounded by curly braces { } . Keys must be strings, and values must be a valid JSON data type (string, number, object, array, boolean or null). Keys and values are separated by a colon.
Variables provide a new way to tackle different scenarios where JSON schema alone fails. This means, that you can use a new keyword named $vars to make your life easier.
Keys must be strings, and values must be a valid JSON data type: string.
Create an object:
var data = {};
Then set the property:
data[key] = value;
Then use the object in your call to $.post()
:
$.post(
"/factory/set",data,
function(response) {
}, "json"
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With