【问题标题】:jquery each running with out waiting ajax statusjquery 每个运行都没有等待 ajax 状态
【发布时间】:2013-10-19 04:15:23
【问题描述】:

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 调用时,继续循环。

【问题讨论】:

    标签: jquery ajax timeout each


    【解决方案1】:

    尝试不使用 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())
    

    【讨论】:

      猜你喜欢
      • 2015-05-10
      • 2015-07-17
      • 2022-01-09
      • 1970-01-01
      • 2020-01-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-13
      相关资源
      最近更新 更多