简体   繁体   中英

How to utilize generic AJAX call with multiple success functions

I am making an ajax call that returns XML. This XML needs to be handled differently based upon the section of the page within the site the user is on. Thus, I would like to implement 1 ajax function that makes the calls, and has a variable success function... I'm sure it is simple but I've searched for a while and cannot figure it out..

function makeAjaxCall(variableSuccessFunction) {
    $.ajax.... (ajax stuff goes here)...
    success: variableSuccessFunction(xml)
}
function ViewOne(xml) {
    //take the XML and update the dom as appropriate
}
function ViewTwo(xml) {
    //take the XML and update the dom as appropriate
}

$(document).ready(function() {
    //be able to call either one of these functions
    makeAjaxCall(ViewOne);
    makeAjaxCall(ViewTwo);

}

You've basically got it! Just one tweak:

function makeAjaxCall(variableSuccessFunction) {
    $.ajax.... (ajax stuff goes here)...
    success: variableSuccessFunction // no (xml)
}

You're passing around function references. success is passed a reference to variableSuccessFunction (whatever that may be) and will call it just like it would if you had supplied an anonymous function to it. No need to invoke it inside of makeAjaxCall .

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