如何利用具有多个成功函数的通用AJAX调用

Cha*_*had 5 javascript jquery

我正在进行一个返回XML的ajax调用.需要根据用户所在站点内的页面部分来不同地处理此XML.因此,我想实现1个调用函数的ajax函数,并且具有可变的成功函数...我敢肯定它很简单,但我已经搜索了一段时间而无法弄明白...

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

}
Run Code Online (Sandbox Code Playgroud)

And*_*ker 4

你基本上已经明白了!只需一项调整:

function makeAjaxCall(variableSuccessFunction) {
    $.ajax.... (ajax stuff goes here)...
    success: variableSuccessFunction // no (xml)
}
Run Code Online (Sandbox Code Playgroud)

您正在传递函数引用。success传递了对(无论是什么)的引用variableSuccessFunction,并且将像您向其提供匿名函数一样调用它。无需在 内调用它makeAjaxCall