【发布时间】:2012-01-11 15:39:13
【问题描述】:
在我的导入照片脚本中,我尝试在带有 Ajax 请求的 while 循环之后更新进度条(Jquery UI)。
JQueryUI 进度条,它应该在 ajax 请求启动之前显示,之后执行。所以我在我的while循环执行结束时有用户反馈......(控制台向我显示这些应用程序运行良好,顺序正确)
想过用live()或者bind(),但是不知道怎么测试……
这是我的 jquery 代码:
$(function() {
var percent_progressbar=0;
$('#myform').submit(function() {
$('#myform').hide();
$("#text_result").html("Import in progress : <span class='progression'>0/0</span>").show(10, function() {
$("#myprogressbar").progressbar({value:percent_progressbar});
$("#myprogressbar").show(10, function() {
if (jQuery.trim($("#id_src").val()).length!=0) {
// Total number of photos to import
$.ajax({
type : 'POST',
async : false,
url : '/nbphotos.php',
data : 'chem=mydir',
success : function(nbphotos){
if (nbphotos>0){
$(".progression").html("0"+" / "+nbphotos);
var finish=false;
var nb_photos_imported=0;
var ajax_done = false;
var resultat_ajax="";
// Variables envoyées en Ajax
var datas = desvariables;
while (nb_photos_imported < nbphotos) {
ajax_done = false;
$.ajax({
type : 'GET',
async : false,
url : '/traitement.php',
data : datas,
success : function(resultat){
resultat_ajax=resultat;
ajax_done=true;
nb_photos_imported++;
}
});
if (ajax_done==true){
if (resultat_ajax=="ok") {
percent_progressbar = Math.floor(nb_photos_imported*100/nbphotos);
$("#myprogressbar").progressbar("option", "value", percent_progressbar);
console.info("Succès ajax (resultat : OK) : "+percent_progressbar);
$(".progression").html(nb_photos_imported+" / "+nbphotos);
} else {
finish=true;
$("#text_result").html(ajax_done);
return false;
}
} else {
// ajax error => exit the while
console.info("Ajax execution error "+nb_photos_imported);
return false;
}
} // While
if (finish==true) {
$("#myprogressbar").hide('slow');
$('#text_result').html("Import of "+nb_photos_imported+" photos done.");
}
} else{
$("#text_result").html("No photo to import.");
$("#myprogressbar").hide(10);
$('#myform').show("slow");
}
}
});
}
});
}); // callback #text_result.show()
return false;
});
});
【问题讨论】:
-
没有时间获得完整的答案,抱歉。 / 因此,简而言之,有几点观察:您在成功回调中设置
ajax_done = true;和nb_photos_imported++;,但在定义ajax 请求后立即对其进行检查。结果将不准确,因为在您运行最后一次检查之前,大多数(所有)请求甚至都不会完成。我建议查看 jQuery 的延迟对象 API:api.jquery.com/category/deferred-object。也许这可以让您了解如何更好地解决这个问题。如果您要进行更改,请发布,我稍后会尝试写一个答案。
标签: jquery-ui jquery progress-bar