2012-02-10 6 views
26

Sono in app mobile e uso multiplo chiamate Ajax per ricevere i dati dal server web come di seguitojquery come utilizzare più chiamate AJAX uno dopo la fine dell'altro

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

Come posso forzare il 2 ° ajax chiama per iniziare dopo la fine del primo ... il terzo dopo la fine del secondo e così via?

+0

L'unica cosa al riguardo è che una chiamata AJAX fallita non comporterà altre chiamate AJAX (perché non c'è "fai questo se la chiamata AJAX fallisce", aspetterà un "successo" per sempre). Forse è esattamente quello che vuoi ... solo qualcosa da considerare. –

+0

Penso che staresti meglio usando $ .quando suggerisce @Lyon. –

risposta

31

Posizionali all'interno dello success: di quello su cui fa affidamento.

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

     // do stuff 

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

come posso fare questo puoi spiegarlo – kosbou

+0

Ripetere per più livelli di chiamate '$ .ajax()'. –

+0

È possibile eseguire in modo ricorsivo questo per un numero sconosciuto di richieste AJAX. Ci sono attualmente un paio di risposte alla domanda che lo dimostrano. – Jasper

8

Avvolgere ogni chiamata Ajax in una funzione denominata e solo li aggiungere alle funzioni di callback di successo della precedente chiamata:

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

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

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


callA(); 
+0

thx per il tuo tempo ...e per la risposta rapida – kosbou

+1

ciò rende il nome della funzione fuorviante: callA non è solo callA, ma anche callB & C – marstone

42

Tu sei un po 'vicino, ma si dovrebbe mettere la vostra funzione all'interno della manifestazione document.ready gestore invece del contrario.

Metti la tua chiamata AJAX in una funzione e lo chiamano dal callback 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(); 
}); 
+2

Questa dovrebbe essere la risposta contrassegnata. Molto bella. – sohtimsso1970

+1

Holy Ajaxception, Batman! questa è certamente una complicazione eccessiva su ciò di cui l'OP ha bisogno. @ La risposta di Lyon è molto più bella. – igorsantos07

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

}); 
6

Si potrebbe anche usare jQuery quando e poi funzioni. per esempio

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

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

+2

come scrivere per 4 livelli di gerarchia? –

+0

E la velocità della prestazione? –

1

io consideri il seguente per essere più pragmatico in quanto non sequenziamento le chiamate Ajax, ma che è sicuramente una questione di gusto.

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

Ora è possibile scorrere window.ajax_call_count all'interno della parte successo delle vostre richieste Ajax fino a raggiungere il numero specificato di chiamate send (window.ajax_calls_completed).

4

Questa è la soluzione più elegante che utilizzo da un po '. Non richiede una variabile contatore esterna e fornisce un buon grado di incapsulamento.

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

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

ajaxRequest(urls); 
-1

Possiamo semplicemente utilizzare

async: false 

questo farà il vostro bisogno.

+0

No, questa è la cosa peggiore che puoi fare perché impacchetta il tuo browser fino a quando una richiesta jax non viene completata. –

Problemi correlati