How to set an object param name with a string in JavaScript?
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.
精彩评论