简体   繁体   English

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

[英]How to utilize generic AJAX call with multiple success functions

I am making an ajax call that returns XML. 我正在进行一个返回XML的ajax调用。 This XML needs to be handled differently based upon the section of the page within the site the user is on. 需要根据用户所在站点内的页面部分来不同地处理此XML。 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.. 因此,我想实现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);

}

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. success传递一个对variableSuccessFunction (无论可能是什么)的引用,并将调用它,就像你向它提供了一个匿名函数一样。 No need to invoke it inside of makeAjaxCall . 无需在makeAjaxCall调用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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