更改AJAX未定义的变量,以便post发挥作用

时间:2012-01-25 23:49:27

标签: javascript jquery ajax post

我在下面的代码中有一些条件变量。例如,如果var shipping ==“true”,则存在shippingAddress1,shippingAddress2等。但是,如果运输==“false”,则这些变量未定义,并留空。我的问题是,当我尝试发布时,我得到一个js错误,因为一些变量是未定义的。有没有办法通过空白发送这些?

$.post( 'reserveAPickupAppointmentCreatePickup.php', {
    'location': appointmentLocation,
    'appointmentAddress1': appointmentAddress1,
    'appointmentAddress2': appointmentAddress2,
    'serviceType': serviceType,
    'shipping': shipping,
    'shippingAddress1': shippingAddress1,
    'shippingAddress2': shippingAddress2,
    'shippingCity': shippingCity,
    'shippingState': shippingState,
    'shippingZip': shippingZip,
    'startTime': startTime,
    'endTime': endTime,
    'date': date,
    'estimatedSize': appointmentSize,
    'highValueItems': highValueItems,
    'insuredItems': insuredItems,
    'tools': tools,
    'presentAtAppointment': presentAtAppointment,
    'contactName': contactName,
    'contactPhone': contactPhone,
    'contactEmail': contactEmail,
    'itemList': itemList,
    'studentPhone': studentPhone
},

3 个答案:

答案 0 :(得分:2)

为您正在使用的变量设置合理的默认值。如果是字符串,则将其默认为空字符串。通常,如果在某些时候没有定义变量,请不要使用变量。

答案 1 :(得分:2)

动态添加它们:

var data = {
    location: appointmentLocation,
    appointmentAddress1: appointmentAddress1,
    appointmentAddress2: appointmentAddress2,
    serviceType: serviceType,
    shipping: shipping
    // etc.
};

if(shipping) {
    data.shippingAddress1 = shippingAddress1;
    data.shippingAddress2 = shippingAddress2;
    // etc.
}

$.post('reserveAPickupAppointmentCreatePickup.php', data);

答案 2 :(得分:0)

理想情况下,您应该声明所有变量,但总是可以执行以下操作:

'foo' : foo || null,
...

不确定$.post是否会喜欢这样。