将动态字段添加到jquery Ajax中

时间:2013-09-11 09:10:25

标签: jquery ajax arrays

我有以下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数据中需要一个额外的字段。你是否被允许在数据字段中的语句? 或者我需要构造数组然后将数组输入数据?我有点困惑。对此最好的做法是什么?

示例:

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
}
这会有用吗?这样做的最佳方式是什么?

1 个答案:

答案 0 :(得分: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
}