当previous一个操作完成多个Ajax调用 [英] Multiple ajax calls when previous one completes

查看:285
本文介绍了当previous一个操作完成多个Ajax调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我还需要这些AJAX调用被调用时,previous一个是成功的,这意味着一旦第一个Ajax是OK,调用第二阿贾克斯,一旦第二Ajax是正常通话3日的,等等等等。我开始与一些Ajax调用,因此被罚款连锁起来像这样的下方,但现在我对他们中的20,这会是一个烂摊子链起来是这样的。

I have these ajax calls that need to get called when the previous one is success, meaning once the first ajax is OK, call the 2nd ajax, once the 2nd ajax is OK call the 3rd one, etc so on. I started with a few ajax calls so it was fine to chain them up like this below but now I have about 20 of them and it'd be a mess to chain them up like this.

$.ajax({
    url: 'urlThatWorks1',
    success: function (data) {

        //call someMethod1 with data;

        $.ajax({
        url: 'urlThatWorks2',
        success: function (data) {

             //call method2 with data;
             //another ajax call ... so on
        } 
 }.... 19 level deep

所以我需要使其更加易于阅读和维护,所以我想是这样

So I need to make it bit easier to read and maintain so I'm thinking something like

var ajaxArray = [];

var function1 = $.ajax('urlThatWorks1', data I get back from the 'urlThatWorks1' call);

myArray.push(function1);

var function2 = $.ajax('urlThatWorks2', data I get back from the 'urlThatWorks2' call);
myArray.push(function2);
//etc 19 others

myArray.each(index, func){
    //Something like $.when(myArray[index].call()).done(... now what?
}

希望这是有道理的,我在寻找Ajax调用数组的方式从中我可以调用它的成功,我所说的数组的下一个AJAX Ajax调用。谢谢你。

Hope this makes sense, I'm looking for a way of ajax call array from which I can call an ajax call on whose success I call the next ajax in the array. Thanks.

推荐答案

创建一个递归函数被调用的顺序为Ajax请求返回的数据。

Create a recursive function to be called in sequence as the ajax requests return data.

var urls = [ "url.1", "url.2", ... ];
var funcs = [];

function BeginAjaxCalls()
{
    RecursiveAjaxCall(0, {});
}

function RecursiveAjaxCall(url_index)
{
    if (url_index >= urls.length)
        return;
    $.ajax(
    {
        url: urls[url_index],
        success: function(data)
        {
            funcs[url_index](data);
            // or funcs[urls[url_index]](data);

            RecursiveAjaxCall(url_index + 1);
        }
    });
}

funcs[0] = function(data)
// or funcs["url.1"] = function(data)
{
    // Do something with data
}

funcs[1] = function(data)
// or funcs["url.2"] = function(data)
{
    // Do something else with data
}

这篇关于当previous一个操作完成多个Ajax调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆