Array with dynamic field names
I am passing this function different field names on each call. I would like it to post the interpolated string value of the variable field
as the name of the posted var. Eg one post might have
data: { 'shoppingCartContents' : cartrow, 'numbe开发者_开发问答r' : number, 'foo' : value }
but every post just has
data: { 'shoppingCartContents' : cartrow, 'number' : number, 'field' : value }
even though field
is not in quotes.
function update_personalization(cartrow, number, field, value) {
$.ajax({
type: 'POST',
url: 'updatePersonalization.php',
data: { 'shoppingCartContents' : cartrow, 'number' : number, field : value }
});
}
What am I doing wrong?
You'll have to build the object differently:
data: (function() {
var rv = {shoppingCartContents: cartrow, number: number};
rv[field] = value;
return rv;
})()
What that does is build up the object you want to pass as "data" in a little anonymous function. The function initializes a simple object with the static field names, then adds the dynamically-named field in a separate statement.
That's not really an "array", for what it's worth.
精彩评论