jQuery ajax 요청이 루프에서 완료될 때까지 기다리는 방법
난 그 코드를 가지고 있다.
for (var i = 0; i < $total_files; i++) {
$.ajax({
type: 'POST',
url: 'uploading.php',
context: $(this),
dataType: 'json',
cache: false,
contentType: false,
processData: false,
data: data_string,
success: function(datas) {
//does something
},
error: function(e) {
alert('error, try again');
}
});
}
이미지를 업로드 할 수 있는 것은 매우 좋지만, 문제는 이미지를 하나씩 업로드하는 방법을 찾을 수 없다는 것입니다.비동기 옵션을 false로 설정하려고 했지만 모든 이미지가 업로드될 때까지 웹 브라우저가 정지됩니다.원하는 이미지가 아닌 이 "async: false" 옵션을 어떻게든 에뮬레이트하여 웹 브라우저를 정지하지 않고 실행할 수 있도록 하고 싶습니다.
어떻게 하는 거죠?
약속 배열을 생성하여 모든 약속이 해결되면 다음 약속을 실행할 수 있습니다.all done코드를 설정합니다.
var promises = [];
for (var i = 0; i < $total_files; i++){
/* $.ajax returns a promise*/
var request = $.ajax({
/* your ajax config*/
})
promises.push( request);
}
$.when.apply(null, promises).done(function(){
alert('All done')
})
네이티브를 지원하는 jQuery 3.x+ 및 최신 브라우저의 경우Promise,Promise.all다음과 같이 사용할 수 있습니다.
var promises = [];
for (var i = 0; i < $total_files; i++) {
// jQuery returns a prom
promises.push($.ajax({
/* your ajax config*/
}))
}
Promise.all(promises)
.then(responseList => {
console.dir(responseList)
})
파일이 이미 목록에 저장되어 있는 경우map루프가 아니라
var fileList = [/*... list of files ...*/];
Promise.all(fileList.map(file => $.ajax({
/* your ajax config*/
})))
.then(responseList => {
console.dir(responseList)
})
각 콜에 어레이를 입력하고, 앞의 콜이 완료되면 다음 아이템을 호출합니다.
다음과 같은 방법을 시도해 볼 수 있습니다.
window.syncUpload = {
queue : [],
upload : function(imagesCount) {
var $total_files = imagesCount, data_string = "";
/* Populates queue array with all ajax calls you are going to need */
for (var i=0; i < $total_files; i++) {
this.queue.push({
type: 'POST',
url: 'uploading.php',
context: $(this),
dataType: 'json',
cache: false,
contentType: false,
processData: false,
data: data_string,
success: function(datas) {
//does something
},
error: function(e){
alert('error, try again');
},
/* When the ajax finished it'll fire the complete event, so we
call the next image to be uploaded.
*/
complete : function() {
this[0].uploadNext();
}
});
}
this.uploadNext();
},
uploadNext : function() {
var queue = this.queue;
/* If there's something left in the array, send it */
if (queue.length > 0) {
/* Create ajax call and remove item from array */
$.ajax(queue.shift(0));
}
}
}
syncUpload.upload(NUMBER_OF_)를 사용하여 호출합니다.이미지);
저는 jQuery를 해보겠습니다.이렇게 해도 비동기 콜을 사용할 수 있지만 지연된 경우, 다음과 같습니다.
jQuery(document).ready(function ($) {
$.when(
//for (var i = 0; i < $total_files; i++) {
$.ajax({
// ajax code
})
//}
).done(function () {
// perform after ajax loop is done
});
}); // ready
EDIT : Ajax 반복은 외부에서 수행해야 합니다.$.whenCharlietfl의 답변에 따라 배열에 밀어넣었습니다.(비동기) Ajax 콜을 사용하여 내부에서 연기할 수 있습니다.$.when단, 'JSFIDLE' 참조
jquery를 사용한 하나의 문장에서
$.when.apply(null, $.map(/*input Array|jQuery*/, function (n, i) {
return $.get(/* URL */, function (data) {
/* Do something */
});
})).done(function () {
/* Called after all ajax is done */
});
언급URL : https://stackoverflow.com/questions/20291366/how-to-wait-until-jquery-ajax-request-finishes-in-a-loop
'source' 카테고리의 다른 글
| 다중 사용자 Ajax 웹 응용 프로그램을 동시에 안전하게 설계하는 방법 (0) | 2023.04.03 |
|---|---|
| Json Schema 유효성 검사: 스키마에 선언된 필드 이외의 필드를 허용하지 않습니다. (0) | 2023.04.03 |
| Scala: JSON을 케이스 클래스로 직접 해석 (0) | 2023.04.03 |
| set 객체는 JSON을 직렬화할 수 없습니다. (0) | 2023.04.03 |
| 절을 사용하여 문 업데이트 (0) | 2023.04.03 |