jquery.ajax函数中的变量:缺少:属性ID之后

时间:2019-03-27 10:16:00

标签: jquery ajax variables

我想在jQuery.ajax {data {action}中使用变量

我收到此错误:

  

SyntaxError:缺少:在属性ID之后

如果我将“ + id +”替换为“ 61”,则可以正常工作。

var id = 61;
jQuery.ajax({
    method: "POST",
    url: "/?someurl",
    data: {
      table: "__databasename",
      action: "edit",
      "data["+id+"][persons]": value
    }
  })
  .done(function(msg) {
    alert("Data Saved: " + msg);
  });

1 个答案:

答案 0 :(得分:0)

"data["+id+"][persons]": value是无效的JS

除非使用新的ES6语法,否则分配的左侧不能有变量:

var dataObj = {
  table: "__databasename",
  action: "edit",
  ["data[" + id + "][persons]"] : value
}

vs

var dataObj = {
  table: "__databasename",
  action: "edit"
};
dataObj["data[" + id + "][persons]"] = value; // standard, assign after

赞:

var value = "zzz";
var id = 61;
var dataObj = {
  table: "__databasename",
  action: "edit",
  ["data[" + id + "][persons]"] : value // ES6
};
// dataObj["data[" + id + "][persons]"] = value; // standard, assign after

console.log(dataObj)
/*
jQuery.ajax({
    method: "POST",
    url: "/?someurl",
    data: dataObj
  })
  .done(function(msg) {
    alert("Data Saved: " + msg);
  });
*/