jquery如何在另一个结束后使用多个ajax调用

kos*_*bou 43 jquery jsonp get function

我在移动应用程序中,我使用多个Ajax调用从Web服务器接收数据,如下所示

function get_json() {
    $(document).ready(function() {
        $.ajax({
            url: 'http://www.xxxxxxxxxxxxx',
            data: {
                name: 'xxxxxx'
            },
            dataType: 'jsonp',
            //jsonp: 'callback',
            //jsonpCallback: 'jsonpCallback',
            success: function(data) {
                $.each(data.posts, function(i, post) {
                    $.mobile.notesdb.transaction(function(t) {
                        t.executeSql('INSERT into bill (barcode, buildingcode, buildingaddress, flatname, flatdescription, entryseason, period, amount, pastpayments, todaypayments, paydate, receiptno) VALUES (?,?,?,?,?,?,?,?,?,?,?,?);', [post.Id, post.Code, post.Address, post.Name, post.Description, post.EntrySeason, post.Period, post.Revenue, post.PastPayments, post.todaypayments, post.paydate, post.receiptno],
                        //$.mobile.changePage('#page3', 'slide', false, true),  
                        null);
                    });
                    $('#mycontent').append(post.Name);
                });
            }
        });

        $.ajax({
            xxxx
        });

        $.ajax({
            xxxx
        });
    });
}
Run Code Online (Sandbox Code Playgroud)

如何强制第二次ajax呼叫在第一次结束后开始...第二次结束后第三次继续?

Tim*_*ron 52

将它们放在success:它所依赖的那个内部.

$.ajax({
    url: 'http://www.xxxxxxxxxxxxx',
    data: {name: 'xxxxxx'},
    dataType: 'jsonp',
    success: function(data){

        // do stuff

        // call next ajax function
        $.ajax({ xxx });
    }
});
Run Code Online (Sandbox Code Playgroud)

  • 您可以对未知数量的 AJAX 请求递归执行此操作。目前有几个问题的答案可以证明这一点。 (2认同)

Jas*_*per 52

你有点接近,但是你应该把你的函数放在document.ready事件处理程序中而不是其他方式.

另一种方法是将AJAX调用放在泛型函数中,并从AJAX回调中调用该函数,按顺序循环遍历一组请求:

$(function () {

    //setup an array of AJAX options,
    //each object will specify information for a single AJAX request
    var ajaxes  = [
            {
                url      : '<url>',
                data     : {...},
                callback : function (data) { /*do work on data*/ }
            },
            {
                url      : '<url2>',
                data     : {...},
                callback : function (data) { /*maybe something different (maybe not)*/ }
            }
        ],
        current = 0;

    //declare your function to run AJAX requests
    function do_ajax() {

        //check to make sure there are more requests to make
        if (current < ajaxes.length) {

            //make the AJAX request with the given info from the array of objects
            $.ajax({
                url      : ajaxes[current].url,
                data     : ajaxes[current].data,
                success  : function (serverResponse) {

                    //once a successful response has been received,
                    //no HTTP error or timeout reached,
                    //run the callback for this request
                    ajaxes[current].callback(serverResponse);

                },
                complete : function () {

                    //increment the `current` counter
                    //and recursively call our do_ajax() function again.
                    current++;
                    do_ajax();

                    //note that the "success" callback will fire
                    //before the "complete" callback

                }
            });
        }
    }

    //run the AJAX function for the first time once `document.ready` fires
    do_ajax();

});
Run Code Online (Sandbox Code Playgroud)

在此示例中,将运行下一个AJAX请求的递归调用设置为complete回调,以便无论当前响应的状态如何,它都会运行.这意味着如果请求超时或返回HTTP错误(或无效响应),则下一个请求仍将运行.如果您要求后续请求仅在请求成功时运行,那么使用success回调进行递归调用可能是最好的.

更新2018-08-21关于评论的好处.

  • 另外,如果你想忽略错误,你可以做一个 `complete: function(){ current++; do_ajax();}` 在那里。:) (2认同)

Sky*_*son 10

在命名函数中包装每个ajax调用,并将它们添加到上一个调用的成功回调中:

function callA() {
    $.ajax({
    ...
    success: function() {
      //do stuff
      callB();
    }
    });
}

function callB() {
    $.ajax({
    ...
    success: function() {
        //do stuff
        callC();
    }
    });
}

function callC() {
    $.ajax({
    ...
    });
}


callA();
Run Code Online (Sandbox Code Playgroud)

  • 这使得函数名具有误导性:callA 不仅是 callA,而且是 callB &amp; C (2认同)

zox*_*xxx 10

这是我一直使用的最优雅的解决方案.它不需要外部计数器变量,它提供了很好的封装程度.

var urls = ['http://..', 'http://..', ..];

function ajaxRequest (urls) {
    if (urls.length > 0) {
        $.ajax({
            method: 'GET',
            url: urls.pop()
        })
        .done(function (result)) {
            ajaxRequest(urls);
        });
    }
}

ajaxRequest(urls); 
Run Code Online (Sandbox Code Playgroud)

  • 这是优雅的 *如果* 除了 URL 之外,每个调用都相同。如果 Ajax 调用涉及不同的方法、返回处理和/或要发送的不同数据,它将变得非常不优雅。在这种情况下,Skyler 上面的解决方案会更加清晰。 (3认同)
  • 嗯,这意味着是基本的例子,但你可以用类似的方式为每个请求定义方法,返回处理和参数.具有创造性.但是对于初学者来说,为每个请求定义新函数可能是更直接的方法.. (2认同)

小智 8

您还可以在使用时使用jquery.例如

 $.when( $.ajax( "test.aspx" ) ).then(function( data, textStatus, jqXHR ) {
  //another ajax call
});
Run Code Online (Sandbox Code Playgroud)

https://api.jquery.com/jQuery.when/

  • 如何写4层次的层次结构? (3认同)