我有一个看起来像这样的函数:
function showCreditCard(idx, data) {
if(typeof cardInfo == 'undefined' && parseInt($("#cc-dropdown-" + idx + " option:selected").val(),10) > -1) {
// actual selection made, but not default, so cardInfo hasn't been set. Need to run ajax call to get credit card;
console.log("show dropdown");
console.log("there are saved cards and a selection was made");
poGetPaymentOption('credit card', parseInt($("#cc-dropdown-" + idx + " option:selected").val(),10), idx);
// this is the default card; display dropdown with default selected and static fields
console.log("supposedly after poGetPayment");
console.dir(cardInfo);
// why is this stuff running before poGetPaymentOtion finishes and returns a cardInfo object?
if( cardInfo.cc.cc_type == 'VI' ) { $('#cc_visaBig-'+idx).attr('class', 'cc_visaBig'); }
$('#cc-static-wrap-'+idx).show();
updateButtonState();
}
}
正如您从注释中看到的那样,poGetPaymentOption
调用之后的行在该函数实际完成之前运行。我也通过poGetPaymentOption
函数中的日志验证了这一点(如下)。
function poGetPaymentOption(type, key, bIdx) {
if( type == 'credit card' ) {
console.log("signed in, credit card");
$.post('/site/ajax/customers/getSingleCreditCard',
{ 'key': key },
function(data) {
if( data.success == 1 ) {
console.log("poPayment success");
if(typeof cardInfo == 'undefined') {
cardInfo = new saveCardInfo(data);
}
} else {
console.log("poPayment no success");
}
}, 'json');
}
}
我期望发生的是调用 from showCreditCard
topoGetPaymentOption
通过 ajax 调用返回成功(它确实如此),然后创建一个saveCardInfo
名为cardInfo
. 据我所知,它确实发生了,但是检查cardInfo.cc.cc_type
和超越的行都是在创建对象之前发生的。我附上了我的 Firebug 控制台的屏幕截图,所以事情发生的顺序很明显。
我究竟做错了什么?在继续使用该功能之前,我需要确保它poGetPaymentOption
已完全完成并cardInfo
已创建。showCreditCard