我有以下ajax代码:
$.ajax({
url: 'library/test.php',
type: 'POST',
data: {
id: id, // label id
field1: field1,
field2: field2,
field3: field3,
field4: field4,
field5: field5,
field6: field6,
field7: field7,
field8: field8,
product: product,
occasion: occasion
},
success: function (res) {
//do something
}
});
现在,如果 id 等于 1,可以说我需要 ajax 数据中的一个额外字段。是否允许在数据字段中使用 if 语句?还是我需要构造数组然后将数组输入到数据中?我有点困惑。对此的最佳做法是什么?
例子:
data: {
id: id, // label id
field1: field1,
field2: field2,
field3: field3,
field4: field4,
field5: field5,
field6: field6,
field7: field7,
field8: field8,
product: product,
occasion: occasion
if (id == 1) {
// very much doubt this will even work
,do: something
}
},
甚至
if (id == 1) {
var array = {"field1": field1, "field2": field2,"do": something};
}
else {
var array {"field1": field1, "field2": field2};
}
data: {
//obviously this would be in the ajax function
array
}
这行得通吗?做这个的最好方式是什么?