2012-03-27 15 views
17

Devo emettere più richieste $ .get, elaborare le loro risposte e registrare i risultati dell'elaborazione nello stesso array. Il codice è simile al seguente:jQuery: Attendi finché non vengono elaborate correttamente più richieste GET

$.get("http://mysite1", function(response){ 
    results[x1] = y1; 
} 
$.get("http://mysite2", function(response){ 
    results[x2] = y2; 
} 

// rest of the code, e.g., print results 

Esiste un modo per garantire che tutte le funzioni di successo hanno completato, prima di procedere con il resto del mio codice?

risposta

34

C'è una soluzione molto elegante: l'oggetto rinviato jQuery. $ .get restituisce un oggetto jqXHR che implementa l'interfaccia differite - questi oggetti possono essere combinati in questo modo:

var d1 = $.get(...); 
var d2 = $.get(...); 

$.when(d1, d2).done(function() { 
    // ...do stuff... 
}); 

saperne di più su http://api.jquery.com/category/deferred-object/ e http://api.jquery.com/jQuery.when/

+0

Questa soluzione funziona ancora se sono presenti funzioni di successo in $ .get chiamate? Ci avevo provato prima, senza fortuna! – amir

+0

Sì, dovrebbe essere possibile. – Niko

10

$.when consente di combinare più Deferred s (che è ciò che $.ajax ritorna).

$.when($.get(1), $.get(2)).done(function(results1, results2) { 
    // results1 and results2 will be an array of arguments that would have been 
    // passed to the normal $.get callback 
}).fail(function() { 
    // will be called if one (or both) requests fail. If a request does fail, 
    // the `done` callback will *not* be called even if one request succeeds. 
}); 
Problemi correlati