views:

526

answers:

4

I'm attempting to pass some data via the jQuery's $.post() and I'm running into some problems with, what I can only classify as, variable evaluation in the data map. Lets get to it:

var field = 'fooVar';
var value = 'barVar';
$.post('/path/to/url', { field:value, 'fooString':'barString' });

The end result is a POST with the following values:

// Actual result
field = barVar
fooString = barString

// Expected result    
foo = barVar
fooString = barString

I expected "field" to be evaluated as the variable "foo" in the data map, but it is not. What I've been able to discern is that the single quotes on the "key" are optional, therefore leaving them out does not cause the variable to evaluated.

I have also tried the following for giggles with the amount of luck:

$.post('/path/to/url', { "'" + field + "'":value, 'fooString':'barString' });
$.post('/path/to/url', { eval(field):value, 'fooString':'barString' });

I'm stumped. Thanks for any help you can provide or even just a firm "no" so I can get on with my life, safe in the knowledge someone more versed has my back would be appreciated. :)

+1  A: 

This is one possible answer.

var field = 'fooVar';
var value = 'barVar'

var data = { fooString:'barString' }
data[field] = value;

$.post('/path/to/url', data);

// Result
fooVar = barVar
fooString = barString

Though, I'm still curious if this can be done inline (like in the original example) rather building the map beforehand.

chuckg
+1  A: 

Correct, a Javascript "map" (object) doesn't evaluate its keys. If you need to evaluate keys, you can do it like so:

var key = 'name';
var value = 'john';
var options = {key: value}; // translates to "key=john"

options[key] = value; // translates to "name=john"

$.post('path', options);
Elliot Nelson
+2  A: 
var field = 'fooVar';
var value = 'barVar';
var postData = {};
postData[field] = value;
postData['fooString'] = 'barString';
$.post('/path/to/url', postData);

Even if there does exist a way to structure this inline (as you hope for here), You're better off doing what you're after by building the object beforehand - see this Encosia article

Skeolan
A: 

If you're set on doing it in a single expression, you could write a helper function like the following (untested):

function objectFromPairs() {
    var o = {};
    for (var i = 0; i < arguments.length; i += 2) {
        o[arguments[i]] = arguments[i+1];
    }
    return o;
}

$.post('/path/to/url', objectFromPairs(field, value, 'fooString', 'barString'));

But as far as using an object literal goes, no, there's no way to use the value of an expression as a key. The properties must be given as either numeric literals, string literals, or valid identifiers (see page 41-42 of the ECMAscript spec).

Miles