Gessle
Gessle

Reputation: 345

jQuery + JSON how to define key from variable

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?

Upvotes: 16

Views: 11276

Answers (1)

Anthony Grist
Anthony Grist

Reputation: 38345

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

Upvotes: 31

Related Questions