简体   繁体   中英

Adding dynamic fields into jquery Ajax

I have the following ajax code:

$.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
    }
});

now if an id is equal to 1 lets say i need an extra field in the ajax data. Are you allowed if statements in the data field? or would i need to construct the array and then input the array into the data? i'm little confussed. What would be the best practice for this?

example:

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
    }
},

or even

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
}

would this work? what is the best way to do this?

You can use conditional operators.

$.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
}

If it's getting complex and you want it to be more readible, you can assign arrays as you've shown.

For example:

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM