0

我有以下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
}

这行得通吗?做这个的最好方式是什么?

4

1 回答 1

3

您可以使用条件运算符。

$.ajax({
url: 'library/test.php',
type: 'POST',
data: {
    id: id, // label id
    field1: field1,
    field2: field2,
    field3: field3,
    field4: field4,
    field5: ((id == 1) ? field5 : "default field5"),
    field6: field6,
    field7: field7,
    field8: field8,
    product: product,   
    occasion: occasion
},
success: function (res) {
    //do something
}

如果它变得越来越复杂并且您希望它更具可读性,则可以按照所示分配数组。

例如:

var dataArray;

if (id == 1) {
    dataArray = {
        id: id, // label id
        field1: field1,
        field2: field2,
    };
}
else {
    dataArray = {
        id: id, // label id
        field4: field4,
        field6: field6,
        field7: field7,
    };
}

$.ajax({
url: 'library/test.php',
type: 'POST',
data: dataArray,
success: function (res) {
    //do something
}
于 2013-09-11T09:13:21.880 回答