jQuery + JSON如何从变量定义键

Ges*_*sle 14 string variables jquery json

我有以下代码

$.post(
    "/factory/set",{
         key : value
    },
    function(response) {

        });
    }, "json"
);
Run Code Online (Sandbox Code Playgroud)

哪里

key = "foo"
value = "bar"
Run Code Online (Sandbox Code Playgroud)

但是服务器总是得到"key"和"bar",有没有办法把键设置为变量,而不是字符串?

Ant*_*ist 29

创建一个对象:

var data = {};
Run Code Online (Sandbox Code Playgroud)

然后设置属性:

data[key] = value;
Run Code Online (Sandbox Code Playgroud)

然后使用您通话中的对象$.post():

$.post(
    "/factory/set",data,
    function(response) {

    }, "json"
);
Run Code Online (Sandbox Code Playgroud)