2012-07-29 280 views
3

我的JavaScript代码 -AJAX函数调用成功

function updateWhatIfPrivacyLevelRemove(recordId, correspondingDetailIDs) { 
    var ajaxCall = $.ajax({ data: { Svc: cntnrRoot, 
     Cmd: 'updateWhatIfPrivacyLevel', 
     updatePrivacyAction: 'Remove', 
     recordID: recordID 
     }, 
     dataType: "text", 
     context: this, 
     cache: false 
    }); 

    $.when(ajaxCall).then(updateWhatIfPrivacyLevelRemoveSuccess(recordID, correspondingResidentDetailIDs)); 
} 

function updateWhatIfPrivacyLevelRemoveSuccess(recordID, correspondingResidentDetailIDs) { 
    //several other lines of non-related code 
      $.ajax({ data: { Svc: cntnrRoot, 
       Cmd: 'handleResidentRow', 
       recordID: 1, 
       active: 0 
      }, 
       dataType: "text", 
       context: this, 
       cache: false 
      }); 
} 

我的C#代码中我处理回调的 'updateWhatIfPrivacyLevel' 和 'handleResidentRow'。我可以告诉在updateWhatIfPrivacyLevel之前调用了handleResidnetRow的AJAX回调。

为什么?

回答

2

当您尝试设置回调时,您实际上是调用的函数。换句话说,你没有像传递回调那样传递“updateWhatIf ...”函数,而是传入它的返回值(看起来它总是undefined)。

尝试此代替:

$.when(ajaxCall).then(function() { 
    updateWhatIfPrivacyLevelRemoveSuccess(recordID, correspondingResidentDetailIDs); 
}); 

到功能名称的引用是对所述功能的对象的引用,并且可以被用来传递函数作为回调。但是,函数后跟()的引用是对函数的调用,该函数将进行评估,以便可以在周围表达式的上下文中使用返回值。因此,在您的代码中,您将undefined(函数调用的结果)传递给.then()方法,这当然不会做到您想要的。

请务必记住,jQuery只是JavaScript,特别是JavaScript函数库。虽然.then()的东西看起来像一个语言构造,它不是— JavaScript解释器不会以任何方式专门处理它。

在我的建议中使用匿名函数的替代方法是在较新的浏览器中的Function原型上使用.bind()方法。这基本上为你做了同样的事情,但它在风格上更像传统的函数式编程。