How can i repeat an Ajax request as long it return 1; if it return 0 it should break
while(1){
$.ajax({
type: "POST",
url: '/admin/importsql/',
data: $datas,
dataType: "json",
success: function($data) {
}})
}
How can i repeat an Ajax request as long it return 1; if it return 0 it should break
while(1){
$.ajax({
type: "POST",
url: '/admin/importsql/',
data: $datas,
dataType: "json",
success: function($data) {
}})
}
2
Answers
You could specify that the AJAX call should be executed synchronously instead of asynchronously. This would afford you the opportunity to set a variable to indicate whether to continue.
To achieve this, simply add the
async
parameter to your AJAX call:In your original code this would be something like:
I should caution though that it would be sensible to catch AJAX failures and errors too, otherwise this could loop indefinitely.
Edit following comment by @Nicolas
It’s important to understand that changing the AJAX call to synchronous will cause the thread to block until the call completes.
This means that any other JS code in the same thread cannot execute whilst the thread is blocked. This may cause an unacceptable impact on your JS applicationwebsite.
You can’t simply do that because ajax is an asynchronous process ( unless specify otherwise, but then what’s the point of using Ajax). You are simply starting noumerous ajax call without waiting for one to finish. What i suggest is to use recursion and promises to send your call one after the other. :
This method chain promises until one of them recieve 0 as a result. Then you can use it as such :
P.S. Please note that this code is untested.