前一个完成时多个ajax调用

时间:2014-09-19 14:24:02

标签: javascript jquery ajax

我有这些ajax调用,当前一个成功时需要调用,这意味着一旦第一个ajax正常,调用第二个ajax,一旦第二个ajax就可以调用第三个,等等。我从一些ajax调用开始,所以可以将它们链接起来,如下所示,但是现在我有大约20个,并且将它们链接起来就像是一团糟。

$.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

所以我需要让它更容易阅读和维护,所以我想像

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。感谢。

4 个答案:

答案 0 :(得分:1)

如何使用延迟方法。类似的东西:



var arrayOfAjaxCalls = [ { url: 'https://api.github.com/', success: function() { $("#results").append("<p>1 done</p>"); } },
                        { url: 'https://api.github.com/', success: function() { $("#results").append("<p>2 done</p>"); } },
                        { url: 'https://api.github.com/', success: function() { $("#results").append("<p>3 done</p>"); } },
                        { url: 'https://api.github.com/', success: function() { $("#results").append("<p>4 done</p>"); } },
                        { url: 'https://api.github.com/', success: function() { $("#results").append("<p>5 done</p>"); } },
                        { url: 'https://api.github.com/', success: function() { $("#results").append("<p>6 done</p>"); } },
                        { url: 'https://api.github.com/', success: function() { $("#results").append("<p>7 done</p>"); } },
                        { url: 'https://api.github.com/', success: function() { $("#results").append("<p>8 done</p>"); } },
                        { url: 'https://api.github.com/', success: function() { $("#results").append("<p>9 done</p>"); } } 
                       ];


loopThrough = $.Deferred().resolve();

$.each(arrayOfAjaxCalls, function(i, ajaxParameters) {
  loopThrough = loopThrough.then(function() {
    return $.ajax(ajaxParameters);
  });
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div id="results"></div>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

创建一个递归函数,以便在ajax请求返回数据时按顺序调用。

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
}

答案 2 :(得分:1)

尝试

$(function () {
    // requests settings , `url` , `data` (if any)
    var _requests = [{
        "url": "/echo/json/",
        "data": JSON.stringify([1])
    }, {
        "url": "/echo/json/",
        "data": JSON.stringify([2])
    }, {
        "url": "/echo/json/",
        "data": JSON.stringify([3])
    }];

    // collect responses
    var responses = [];

    // requests object ,
    // `deferred` object , `queue` object
    var requests = new $.Deferred() || $(requests);

    // do stuff when all requests "done" , completed
    requests.done(function (data) {
        console.log(data);
        alert(data.length + " requests completed");
        $.each(data, function (k, v) {
            $("#results").append(v + "\n")
        })
    });

    // make request
    var request = function (url, data) {
        return $.post(url, {
            json: data
        }, "json")
    };

    // handle responses
    var response = function (data, textStatus, jqxhr) {
        // if request `textStatus` === `success` ,
        // do stuff
        if (textStatus === "success") {
            // do stuff 
            // at each completed request , response
            console.log(data, textStatus);
            responses.push([textStatus, data, $.now()]);
            // if more requests in queue , dequeue requests
            if ($.queue(requests, "ajax").length) {
                $.dequeue(requests, "ajax")
            } else {
                // if no requests in queue , resolve responses array
                requests.resolve(responses)
            }
        };
    };

    // create queue of request functions
    $.each(_requests, function (k, v) {
        $.queue(requests, "ajax", function () {
            return request(v.url, v.data)
            .then(response /* , error */ )
        })
    })

        $.dequeue(requests, "ajax")

});

jsfiddle http://jsfiddle.net/guest271314/6knraLyn/

请参阅jQuery.queue()jQuery.dequeue()

答案 3 :(得分:0)

您可以使用异步库,它具有一系列功能,如瀑布或系列,可以解决您的问题。

https://github.com/caolan/async#series

https://github.com/caolan/async#waterfall