简体   繁体   中英

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 make 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: ... }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM