延迟对象[docs]非常适合这一点。不幸的是,您的代码示例包含语法错误,并且不清楚调用是如何嵌套的。因此,我不确定您是要一个接一个地运行两个 Ajax 调用还是并行运行,但任何一种方式都是可能的。
这里有两个例子。查看文档以获取更多信息并尝试使用它。
注意: .postJSON
不是内置的 jQuery 方法,我在这里假设您从$.ajax
(or $.post
) 函数返回返回值。
并行 Ajax 调用:
$.getSomeData = function() {
var a = $.postJSON("iwantdata.htm", {data:data});
var b = $.postJSON("iwantmoredata.htm", {data:data});
// return a new promise object which gets resolved when both calls are
// successful
return $.when(a, b);
};
// when both calls are successful, call `$.useSomeData`
// it will have access to the responses of both Ajax calls
$.getSomeData.done($.useSomeData);
看: $.when
链式 Ajax 调用:
...第一个调用的响应是第二个调用的输入。这只是一个例子,当然你可以传递任何你想要的数据。
$.getSomeData = function() {
return $.postJSON("iwantdata.htm", {data:data}).pipe(function(response) {
// execute the second Ajax call upon successful completion
// of the first one
return $.postJSON("iwantmoredata.htm", {data:response});
});
};
// if both Ajax calls are successful, call `$.useSomeData`
// it will have access to the response of the second Ajax call
$.getSomeData.done($.useSomeData);
看: deferred.pipe()
如果您有更复杂的逻辑,您还可以创建、解析或拒绝您自己的延迟对象。查看文档中的示例。