开发者

How to set an object param name with a string in JavaScript?

开发者 https://www.devze.com 2023-03-14 16:09 出处:网络
I\'m writing a pl开发者_StackOverflow中文版ugin for jQuery where I need to send a little piece of data to the server, but I need to set the var name of the json object I send:

I'm writing a pl开发者_StackOverflow中文版ugin for jQuery where I need to send a little piece of data to the server, but I need to set the var name of the json object I send:

var params = {name:'var_name'}
$.post('page.php', {params.name:'the value'}, function () { /* etc. */ });

how can I do it?


Use the array access syntax:

var params={};
params['varName']='a value';
$.post('...', params, function() {
    ...
});


Define the object before the $.post() call. A little something like this:

// variable somePropertyName holds the name of the property you want to set    
var myPostParams = {};
myPostParams[somePropertyName] = "some value";

$.post('page.php', myPostParams, function () { /* etc. */ });   

Note that if some of the parameters you are passing will be constant you can define them up front:

var myPostParams = {"x" : "something", "y" : "something else"};
myPostParams[someVariablePropertyName] = "another value";
myPostParams[someOtherPropertyName] = aValueInAVariable;
//etc.
0

精彩评论

暂无评论...
验证码 换一张
取 消