2012-01-25 28 views
1

我在下面的代碼中有一些條件變量。例如,如果var shipping ==「true」,則存在shippingAddress1,shippingAddress2等。但是,如果shipping ==「false」,這些變量是未定義的,並留空。我的問題是,當我嘗試發佈時,由於某些變量未定義,我收到了一個js錯誤。有沒有辦法將這些通過空白?更改AJAX未定義變量,以便發佈將工作

$.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 
}, 
+0

如果您正在尋找窗體域,用[連載](http://api.jquery.com/serialize/) – epascarello

回答

2

爲您正在使用的變量設置合理的默認值。如果它是一個字符串,則默認爲一個空字符串。一般情況下,如果在某個時刻尚未定義變量,則不要使用變量。

+0

所以我必須這樣做,一個接一個在我定義每個變量的時候?我希望能夠同時捕捉所有這些字符串,並將它們設置爲一個空字符串......並且我假設我只是通過將其設置爲「」正確設置一個空字符串? – radleybobins

+0

我會這樣做,你聲明每個變量。我通常會將所有變量聲明在我的詞法範圍的頂部,並在合理的默認情況下同時定義它們。是的,一個空字符串只會是「」或「' – kinakuta

+0

謝謝,我結束了使用這種方法,感謝您的幫助!如果我最終一次完成所有工作,那麼我需要編寫幾個條件語句,這樣做更簡單。 – radleybobins

0

理想情況下,你應該聲明所有的變量,但你總是可以這樣做:

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

不知道$.post會喜歡這一點。

+0

我不知道,但它是值得一試 – radleybobins

+0

不,它似乎並沒有那樣,但多謝 – radleybobins

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

這是一個很好的建議,但有太多的條件 – radleybobins

+0

@radleybobins:呃..不,看起來不像。做你已經做的事情,並按照實際情況在'if'中包裝特定的運輸工具。這並不困難。 – Ryan

+0

如果我的條件較少,我一定會記住這一點,但有幾種情況......航運只是一個例子......我最終回過頭來將變量定義爲空字符串,應該找到我的目的 – radleybobins