Подтвердить что ты не робот

Jquery как использовать несколько вызовов ajax один за другим

Я в мобильном приложении, и я использую несколько вызовов Ajax для приема данных с веб-сервера, как показано ниже.

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
        });
    });
}

Как я могу заставить второй вызов ajax начать после окончания первого... третьего после окончания второго и так далее?

4b9b3361

Ответ 1

Поместите их внутри success: того, на который он опирается.

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

        // do stuff

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

Ответ 2

Вы немного близки, но вы должны поместить свою функцию внутри обработчика событий document.ready вместо обратного пути.

Поместите вызов AJAX в функцию и вызовите его из обратного вызова AJAX:

$(function () {

    //setup an array of AJAX options, each object is an index that will specify information for a single AJAX request
    var ajaxes  = [{ url : '<url>', dataType : 'json' }, { url : '<url2>', dataType : 'xml' }],
        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 data from the `ajaxes` array of objects
            $.ajax({
                url      : ajaxes[current].url,
                dataType : ajaxes[current].dataType,
                success  : function (serverResponse) {
                    ...
                    //increment the `current` counter and recursively call this function again
                    current++;
                    do_ajax();
                }
            });
        }
    }

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

Ответ 3

Оберните каждый вызов ajax в именованную функцию и просто добавьте их в обратные вызовы успешного вызова:

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

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

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


callA();

Ответ 4

Вы также можете использовать jquery, когда и затем выполняете функции. например

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

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

Ответ 5

Это наиболее элегантное решение, которое я использовал некоторое время. Он не требует внешней переменной счетчика и обеспечивает хорошую степень инкапсуляции.

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

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

ajaxRequest(urls); 

Ответ 6

Я считаю следующее более прагматичным, поскольку он не упорядочивает вызовы 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);

Теперь вы можете выполнить итерацию window.ajax_call_count внутри части успеха ваших запросов ajax, пока не достигнет указанного количества вызовов send (window.ajax_calls_completed).

Ответ 7

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

});

Ответ 8

Мы можем просто использовать

async: false 

Это поможет вам.