Pętlę przez tablicę uruchamiającą dla każdego żądania ajax. Potrzebuję, aby żądania były realizowane w kolejności, więc mogę odebrać ostatnie żądanie i uruchomić funkcję po pomyślnym zakończeniu.
w tej chwili jestem uruchomiony (uproszczony):
$.each(array, function(i, item){
ajax_request(item.id, item.title, i);
})
function ajax_request(id, title, i){
$.ajax({
async: false,
url: "url here",
success: function(){
if(i == array.length-1){
// run function here as its the last item in array
}
}
})
}
jednak za pomocą asynchronizacji:false powoduje, że aplikacja nie odpowiada / spowalnia. ale bez asynchronizacji: fałsz czasami jedno z żądań zawiesza się i faktycznie powraca po zwróceniu ostatniego wysłanego żądania ajax.
jak mogę to zaimplementować bez użycia asynchronizacji: fałsz?
Odpowiedzi:
5 dla odpowiedzi № 1Możesz użyć funkcji lokalnej do uruchomienia wywołania ajax i w każdej kolejnej procedurze obsługi sukcesu możesz rozpocząć następne wywołanie ajax.
function runAllAjax(array) {
// initialize index counter
var i = 0;
function next() {
var id = array[i].id;
var title = array[i].title;
$.ajax({
async: true,
url: "url here",
success: function(){
++i;
if(i >= array.length) {
// run function here as its the last item in array
} else {
// do the next ajax call
next();
}
}
});
}
// start the first one
next();
}
Aktualizacja tej odpowiedzi w 2016 r. O opcję wykorzystującą obietnice. Oto jak uruchamiasz żądania szeregowo:
array.reduce(function(p, item) {
return p.then(function() {
// you can access item.id and item.title here
return $.ajax({url: "url here", ...}).then(function(result) {
// process individual ajax result here
});
});
}, Promise.resolve()).then(function() {
// all requests are done here
});
Oto jak je równolegle uruchamiać, zwracając wszystkie wyniki:
var promises = [];
array.forEach(function(item) {
// you can access item.id and item.title here
promises.push($.ajax({url: "url here", ...});
});
Promise.all(promises).then(function(results) {
// all ajax calls done here, results is an array of responses
});
1 dla odpowiedzi nr 2
Możesz umieścić swój kod AJAX w osobnej funkcji i za każdym razem, gdy zakończy się żądanie, może wywołać tę metodę i przekazać jej tożsamość, która zostanie zwiększona dla następnego żądania.
1 dla odpowiedzi nr 3
Spróbuj $ .when ()
var requests = $.map(array, function (i, item) {
return ajax_request(item.id, item.title, i);
});
$.when.apply($, requests).done(function(){
$.each(arguments, function(i, params){
var data = params[0];
//do your stuff
})
})
function ajax_request(id, title, i) {
return $.ajax({
async: false,
url: "url here"
})
}