简体   繁体   中英

AJAX function calling on success

My javascript code -

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

within my C# code I handle the call backs for 'updateWhatIfPrivacyLevel' and 'handleResidentRow'. I can tell that the AJAX callback to handleResidnetRow is called before updateWhatIfPrivacyLevel.

Why?

When you're trying to set up the callback, you're actually calling the function. In other words, you're not passing that "updateWhatIf..." function as the callback, you're passing in its return value (which looks like it'd always be undefined ).

Try this instead:

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

A reference to a function name is a reference to the function as object, and can be used to pass the function as a callback. However, a reference to a function followed by ( ) is a call to the function, which will be evaluated so that the return value can be used in the context of the surrounding expression. Thus, in your code, you pass undefined (the result of the function call) to the .then() method, which of course won't do what you want.

It's important to keep in mind that jQuery is just JavaScript, and in particular a JavaScript function library. Though the .then() thing looks like a language construct, it isn't — the JavaScript interpreter doesn't treat it specially in any way.

An alternative to using an anonymous function as in my suggestion is to use the .bind() method on the Function prototype in newer browsers. That basically does the same thing for you, but it's stylistically more like traditional functional programming.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM