开发者

Javascript jQuery replace a variable with a value

I have this line of Javascript jQuery code

$.post('/blah', { comment_id: 1, description: ... });

However, what I really need is the ability to change comment_id to something else on the fly, how do I m开发者_如何学Goake that into a variable that I can change?

EDIT

Clarification, I meant changing the value of comment_id to say photo_id, so the left side of the assignment.


Use a javascript variable: https://developer.mozilla.org/en/JavaScript/Guide/Values,_Variables,_and_Literals

 var commentId = 1;
 $.post('/blah', { comment_id: commentId, description: ... });

EDIT:

var data = {}; // new object
data['some_name'] = 'some value';
data['another_name'] = true;
$.post('/blah', data);  // sends some_name=some value&another_name=true

EDIT 2:

$.post('/blah', (function () { var data = {}; // new object
  data['some_name'] = 'some value';
  data['another_name'] = true;
  return data;
}()));


function doIt(commentId) {
  $.post('/blah', { comment_id: commentId, description: ... });
}

Thanks to the clarification from Cameron, here's an example that does what the OP actually asked for, that is to make a property name in the object dynamic.

function doIt(name, value) {
  var options = {description: '', other_prop: ''};
  // This is the only way to add a dynamic property, can't use the literal
  options[name] = value;
  $.post('/blah', options);
}


Assign the object to a variable first so that you can manipulate it:

var comment_id = 17;
var options =  { description: ... };
options[comment_id] = 1;  // Now options is { 17: 1, description: ... }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜