我需要在 jQuery .each 之后執行一些代碼
我試圖在每個回圈之后寫入它,但它會立即執行。我已經嘗試過 .promise().done,但這給了我一個錯誤,promise() 不是一個函式。
我的代碼
$("#loader").show();
var url = $(this).attr("action");
var formData = new FormData($(this)[0]);
$(this).hide();
$.ajax({
url: "generateJson.php",
type: 'POST',
data: formData,
async: true,
cache: false,
contentType: false,
enctype: 'multipart/form-data',
processData: false,
success: function (data, status)
{
$('#json').append(data); //content loads here
},
error: function (xhr, desc, err)
{
console.log("error");
}
}).done(function( data ) {
data = JSON.parse( $("#json").val() );
//console.log(data.length);
$.each( data, function( key, val ) {
console.log(val);
//$("#result").append(val);
$.ajax({
type: "POST",
url: "/generateInvoice.php",
dataType: "html",
data: val,
success: function (data, status) {
//console.log(data);
if (data) {
$("#result").append(data)
// console.log("Hurray");
} else {
console.log("Error");
}
},
error: function (xhr, desc, err)
{
console.log("error: " desc " " err);
}
});
}).promise().done(function(){
$("#loader").hide();
$("#done").show();
});
});
uj5u.com熱心網友回復:
您正在使用.success和。done,所以我洗掉了一個。兩者都不需要。此外,為了更容易閱讀/排除故障,我將 post-ajax 代碼移到了它自己的函式中。我不確定你為什么要寫到一個 div 然后再讀回來,所以我離開了,但把它注釋掉了。最后,我添加了一個簡單的計數器來迭代您正在進行的后續 ajax 呼叫,以便它可以檢測到一切何時完成。我從這篇文章中竊取了這個想法。
$("#loader").show();
var url = $(this).attr("action");
var formData = new FormData($(this)[0]);
$(this).hide();
$.ajax({
url: "generateJson.php",
type: 'POST',
data: formData,
async: true,
cache: false,
contentType: false,
enctype: 'multipart/form-data',
processData: false,
error: function(xhr, desc, err) {
console.log("error");
}
}).done(function(data) {
$('#json').append(data); //content loads here
runPostAjax(data)
}),
error: function(xhr, desc, err) {
console.log("error: " desc " " err);
}
});
function runPostAjax(data) {
//data = JSON.parse($("#json").val());
let done = data.length; // number of total requests
$.each(data, function(key, val) {
$.ajax({
type: "POST",
url: "/generateInvoice.php",
dataType: "html",
data: val,
success: function(data, status) {
if (data) {
$("#result").append(data)
done -= 1;
if (done == 0) {
$("#loader").hide();
$("#done").show();
}
} else {
console.log("Error");
}
})
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/389896.html
標籤:查询
