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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9235237/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 10:31:57  来源:igfitidea点击:

jquery how to use multiple ajax calls one after the end of the other

jqueryfunctiongetjsonp

提问by kosbou

I am in mobile app and I use multiple Ajax calls to receive data from web server like below

我在移动应用程序中,我使用多个 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
        });
    });
}

How can I force the 2nd ajax call to begin after the end of the first... the 3rd after the end of the 2nd and so go on?

如何强制第二个 ajax 调用在第一个结束后开始......第二个结束后的第三个等等继续?

回答by Timothy Aaron

Place them inside of the success:of the one it relies on.

将它们放在success:它所依赖的那个里面。

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

        // do stuff

        // call next ajax function
        $.ajax({ xxx });
    }
});

回答by Jasper

You are somewhat close, but you should put your function inside the document.readyevent handler instead of the other-way-around.

你有点接近,但你应该把你的函数放在document.ready事件处理程序中,而不是反过来。

Another way to do this is by placing your AJAX call in a generic function and call that function from an AJAX callback to loop through a set of requests in order:

另一种方法是将 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();

});

In this example, the recursive call to run the next AJAX request is being set as the completecallback so that it runs regardless of the status of the current response. Meaning that if the request times out or returns an HTTP error (or invalid response), the next request will still run. If you require subsequent requests to only run when a request is successful, then using the successcallback to make your recursive call would likely be best.

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

Updated 2018-08-21 in regards to good points in comments.

更新 2018-08-21 关于评论中的优点。

回答by zoxxx

This is the most elegant solution I've been using for a while.It doesn't require external counter variable and it provides nice degree of encapsulation.

这是我使用了一段时间的最优雅的解决方案。它不需要外部计数器变量,并且提供了很好的封装度。

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

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

ajaxRequest(urls); 

回答by Skylar Anderson

Wrap each ajax call in a named function and just add them to the success callbacks of the previous call:

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

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

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

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


callA();

回答by Lyon

You could also use jquery when and then functions. for example

您还可以使用 jquery when and then 函数。例如

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

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

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

回答by arunzer

I consider the following to be more pragmatic since it does not sequence the ajax calls but that is surely a matter of taste.

我认为以下更实用,因为它没有对 ajax 调用进行排序,但这肯定是一个品味问题。

function check_ajax_call_count()
{
    if ( window.ajax_call_count==window.ajax_calls_completed )
    {
        // do whatever needs to be done after the last ajax call finished
    }
}
window.ajax_call_count = 0;
window.ajax_calls_completed = 10;
setInterval(check_ajax_call_count,100);

Now you can iterate window.ajax_call_count inside the success part of your ajax requests until it reaches the specified number of calls send (window.ajax_calls_completed).

现在,您可以在 ajax 请求的成功部分内迭代 window.ajax_call_count,直到达到指定的调用发送次数 (window.ajax_calls_completed)。

回答by adityajain019

Haven't tried it yet but this is the best way I can think of if there umpteen number of ajax calls.

还没有尝试过,但如果有无数的 ajax 调用,这是我能想到的最好方法。

Method1:

方法一:

let ajax1= $.ajax({url:'', type:'', . . .});
let ajax2= $.ajax({url:'', type:'', . . .});
.
.
.
let ajaxList = [ajax1, ajax2, . . .]

let count = 0;
let executeAjax = (i) => {
   $.when(ajaxList[i]).done((data) => {
      //  dataOperations goes here
      return i++
   })
}
while (count< ajaxList.length) {
   count = executeAjax(count)
}

If there are only a handful you can always nest them like this.

如果只有少数,你总是可以像这样嵌套它们。

Method2:

方法二:

$.when(ajax1).done((data1) => {
      //  dataOperations goes here on data1
      $.when(ajax2).done((data2) => {
         //  Here you can utilize data1 and data 2 simultaneously 
         . . . and so on
      })
   })

Note:If it is repetitive task go for method1, And if each data is to be treated differently, nesting in method2makes more sense.

注意:如果是重复性任务,则选择method1,如果要对每个数据进行不同的处理,则在method2 中嵌套更有意义。

回答by Avinash Saini

$(document).ready(function(){
 $('#category').change(function(){  
  $("#app").fadeOut();
$.ajax({
type: "POST",
url: "themes/ajax.php",
data: "cat="+$(this).val(),
cache: false,
success: function(msg)
    {
    $('#app').fadeIn().html(msg);
    $('#app').change(function(){    
    $("#store").fadeOut();
        $.ajax({
        type: "POST",
        url: "themes/ajax.php",
        data: "app="+$(this).val(),
        cache: false,
        success: function(ms)
            {
            $('#store').fadeIn().html(ms);

            }
            });// second ajAx
        });// second on change


     }// first  ajAx sucess
  });// firs ajAx
 });// firs on change

});

回答by rahul singh

We can simply use

我们可以简单地使用

async: false 

This will do your need.

这将满足您的需要。