2012-07-29 230 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()方法。這基本上爲你做了同樣的事情,但它在風格上更像傳統的函數式編程。