有没有办法让var changes
成为可以放入下面这个数组的变量?
$(".SUBMIT").on("click", function(){
var name = $("#idvalue").val();
var changes = "thischanges"; // this variable changes the key
$.post("ajax_process.php",{ changes: name}, function(data){
alert(data);
});
});// END submit
$_POST['changes']; // will be what sends through, is there a way to make it the variable every time?
这与key, value
类似,但会生成一个随变量变化的键。
答案 0 :(得分:2)
您需要分两步构造对象,并使用bracket notation作为变量属性名称:
$(".SUBMIT").on("click", function(){
var name = $("#idvalue").val();
var changes = "thischanges";
var data = {}
data[changes] = name; // set dynamic property name
$.post("ajax_process.php", data, function(data){
alert(data);
});
});
使用ES2015标准,您可以使用computed property names:
$(".SUBMIT").on("click", function(){
var name = $("#idvalue").val();
var changes = "thischanges";
$.post("ajax_process.php",{[changes]: name}, function(data){
alert(data);
});
});