In the application I am working, the server pages are used to recieving an input\'s name as the key for it\'s value. Is is possible to do this with ajax? In this example, t
Unfortunately, inside an object initialiser the part on the left side of the :
is not treated as a variable but as a string, so the_key
is regarded the same as "the_key"
.
This is the most straightforward way I can think of to add properties with a dynamic name:
var fields = {
p_session_id: $("[name='p_session_id']").val(),
p_username: $("[name='p_username']").val()
}
fields[thisName] = thisValue;
Then use fields
in your $.ajax
call as data: fields
Perhaps not quite as elegant but :
function makeObj (a) {
if (!(a instanceof Array))
throw ('Attempt to build object from ' + (typeof a));
if (a.length % 2)
throw ('Attempt to build object from an array length ' + a.length);
for (var o = {}, i = a.length - 1; i > 0; i -= 2) {
console.log (a[i-1], a[i]);
o[a[i - 1]] = a[i];
}
return o;
}
var thisName = 'Hans PUFAL';
var thisValue = 'Paleoinformaticien';
var session_id = '123edrft456fg';
var o = makeObj (['p_session_id', session_id,
'p_username', 'HBP',
thisName, thisValue]);
Available here : http://jsfiddle.net/jstoolsmith/bZtpQ