我正在阅读有关此主题的所有其他问题,但似乎找不到我的代码的最佳选择。基本上我有一个.each
迭代器来执行异步ajax函数。我需要在不锁定浏览器的情况下实现同步,因此我选择不使用async: false
。
以下是代码:
$(".btn-timbrar").each(function(i, obj){
$.ajax({
type: 'POST',
url: "Home?opt=Recibo_G",
data: {id: $(obj).data("id"), p: pago},
success: function(response){
progress = progress + interval;
$barra.find("#progreso-global").width(progress);
$barra.find("#progreso-global").html(progress+"%");
if(response.indexOf("timbrado con exito") != -1){
$(obj).parent().html('<a title="PDF" class="btn btn-recibo-info btn-mini" target="_blank" href="/ReciboVital/Home?opt=PDF&id='+$(obj).data("id")+'"><span class="glyphicon glyphicon-file"></span> PDF</a> <a title="XML" class="btn btn-recibo-info btn-mini" target="_blank" href="/ReciboVital/Home?opt=XML&id='+$(obj).data("id")+'"><span class="glyphicon glyphicon-download-alt"></span> XML</a> <a title="Enviar Correo" class="btn btn-recibo-info btn-mini btn-correo" href="/ReciboVital/Home?opt=Correo&='+$(obj).data("id")+'"><span class="glyphicon glyphicon-envelope"></span></a> <a title="Cancelar" class="btn btn-recibo-info btn-mini btn-correo" href="/ReciboVital/Home?opt=Cancelar&id='+$(obj).data("id")+'"><span class="glyphicon glyphicon-remove"></span></a>');
$("#example thead th:eq(5)").width(150);
}
}
});
});
答案 0 :(得分:0)
在不使用async: false
的情况下执行此操作的唯一方法是使用回调而不是.each()
循环。例如:
var buttons = $(".btn-timbrar");
(function nextButton() {
var obj = [].pop.call(buttons);
$.ajax({
type: 'POST',
url: "Home?opt=Recibo_G",
data: {id: $(obj).data("id"), p: pago},
success: function(response){
progress = progress + interval;
$barra.find("#progreso-global").width(progress);
$barra.find("#progreso-global").html(progress+"%");
if(response.indexOf("timbrado con exito") != -1){
$(obj).parent().html('<a title="PDF" class="btn btn-recibo-info btn-mini" target="_blank" href="/ReciboVital/Home?opt=PDF&id='+$(obj).data("id")+'"><span class="glyphicon glyphicon-file"></span> PDF</a> <a title="XML" class="btn btn-recibo-info btn-mini" target="_blank" href="/ReciboVital/Home?opt=XML&id='+$(obj).data("id")+'"><span class="glyphicon glyphicon-download-alt"></span> XML</a> <a title="Enviar Correo" class="btn btn-recibo-info btn-mini btn-correo" href="/ReciboVital/Home?opt=Correo&='+$(obj).data("id")+'"><span class="glyphicon glyphicon-envelope"></span></a> <a title="Cancelar" class="btn btn-recibo-info btn-mini btn-correo" href="/ReciboVital/Home?opt=Cancelar&id='+$(obj).data("id")+'"><span class="glyphicon glyphicon-remove"></span></a>');
$("#example thead th:eq(5)").width(150);
}
if(buttons.length > 0) {
nextButton();
}
}
});
})();