Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript variable evaluation in a map

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. :)

like image 956
chuckg Avatar asked Apr 10 '09 23:04

chuckg


1 Answers

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

like image 154
Skeolan Avatar answered Sep 18 '22 20:09

Skeolan