0

jquery 中的 .each 方法不会等到成功的 ajax 调用。

$("img[name='statusIcon']").each(function () {
    var statusIcon = $(this);
    statusIcon.attr('src', 'images/spinner.gif'); //loading image will be here
    var row = $(this).parent().parent().attr("id");
    var HostName = $("#" + row + " td[name='Public']").attr("title");
    var Pass = $.trim($("#pass_word" + row).attr("realValue"));
    $.ajax({
        type: "POST",
        url: "validate.php",
        data: "HostName=" + HostName + "&uName=root&Pass=" + Pass + "&localCounter=" + stepCounter,
        success: function (res) {
            console.log(res);
            if (res == 0) {
                statusIcon.attr('src', 'images/tick-mark.jpg'); //success image will be here
            } else {
                statusIcon.attr('src', 'images/cross_icon.jpg'); //fail image will be here
            }
        }
    });
});

这是代码FIDDLE

.each 完成,直到我的第一个 ajax 调用响应,而它应该为每个 ajax 调用循环。
当它完成上一个 ajax 调用时,继续循环。

4

1 回答 1

0

不使用 async:false 的尝试

function doSomething(array){
    if(array.length == 0){
        return;
    }
    var statusIcon = $(array.shift());
    statusIcon.attr('src', 'images/spinner.gif'); //loading image will be here
    var row = $(this).parent().parent().attr("id");
    var HostName = $("#" + row + " td[name='Public']").attr("title");
    var Pass = $.trim($("#pass_word" + row).attr("realValue"));
    $.ajax({
        type: "POST",
        url: "validate.php",
        data: "HostName=" + HostName + "&uName=root&Pass=" + Pass + "&localCounter=" + stepCounter,
        success: function (res) {
            if (res == 0) {
                statusIcon.attr('src', 'images/tick-mark.jpg'); //success image will be here
            } else {
                statusIcon.attr('src', 'images/cross_icon.jpg'); //fail image will be here
            }
        }
    }).always(function(){
        doSomething(array)
    });
}
doSomething($("img[name='statusIcon']").get())
于 2013-10-11T07:16:12.377 回答