Yes we can! Dose something like this work for you?
function first() {
var a = $.ajax({
// ...
});
return a.promise();
}
first().done(function(){
//Im done
});
سؤال
I need to wait for a certain ajax request to complete before going on. Since this request is triggered from different anchors, I wrapped it in a function. What happens after the function with the first ajax has finished, is a second ajax request.
At first, I tried to wait for the first to finish using $.ajaxComplete()
which ran into an endless loop because of the second ajax request performed thereafter.
I found some samples about using $.when
but none of them showed whether it's possible to use a method instead deferreds.
Here's what I'd like to do:
$.when( functionFirstAjaxCall(data) ).then( function() {
// after first ajax request has finished, do the following:
$.ajax({
//...
});
});
Does functionFirstAjaxCall()
need to have a certain return value or how can I get this one working? By the way, the solution doesn't need to use $.when
.
Update: I got it working by creating a custom event as Vandesh has advised.
function first() {
$.ajax({
// ...
success: function (d) {
$.event.trigger({
type: "finished",
data: d
});
}
});
}
$(document).on('finished', second());
Anyway, would there be a simple solution by using $.when
?
المحلول
Yes we can! Dose something like this work for you?
function first() {
var a = $.ajax({
// ...
});
return a.promise();
}
first().done(function(){
//Im done
});
نصائح أخرى
You can do something like -
$.ajax({// First AJAX call
url: ""
}).done(function() {
$.ajax({//Second AJAX call on completion of first
url: ""
}).done(function() {
});
});
Find more on usage of $.ajax()