【问题标题】:Changing AJAX undefined variables so that post will work更改 AJAX 未定义的变量,以便发布工作
【发布时间】:2012-02-19 04:40:03
【问题描述】:

我在下面的代码中有一些条件变量。例如,如果 var shipping == "true",则 shippingAddress1、 shippingAddress2 等存在。但是,如果 shipping == "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
},

【问题讨论】:

  • 如果您正在查找表单字段,请使用serialize

标签: javascript jquery ajax post


【解决方案1】:

动态添加它们:

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);

【讨论】:

  • 这个建议不错,但是条件太多了
  • @radleybobins:呃……不,看起来不像。做你已经在做的事情,并将运输特定的包裹在if 中,如图所示。这不是很困难。
  • 如果我有更少的条件,我当然会记住这一点,但是有几种情况......运输只是一个例子......我最终只是返回并将变量定义为空字符串,应该可以为我的目的找到
【解决方案2】:

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

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

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

【讨论】:

  • 我也不确定,但值得一试
【解决方案3】:

为您使用的变量设置合理的默认值。如果是字符串,则默认为空字符串。一般来说,如果变量没有被定义,就不要使用它们。

【讨论】:

  • 所以我必须在定义每个变量的时候一个一个地做这个?我希望有一种方法可以同时捕获所有这些并将它们设置为一个空字符串......我假设我只是通过将其设置为“”来设置一个空字符串正确?
  • 我会在你声明每个变量的地方做。我通常在我的词法范围的顶部声明我的所有变量,并使用合理的默认值同时定义它们。是的,一个空字符串就是 "" 或 ''
  • 谢谢,我最终使用了这个方法,谢谢你的帮助!如果我最后一次完成,我需要写几个条件语句,这更容易。
猜你喜欢
  • 2017-10-29
  • 2019-07-07
  • 1970-01-01
  • 1970-01-01
  • 2021-08-07
  • 2017-11-18
  • 2023-01-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多