1

basically I want a Jquery function to call a PHP script multiple times, and every single time, load the response into a div, this is the code I have now:

images = 10;
while(images > 0)
    {
        $.ajax({        
            type: "POST",
            url: "processimage.php",
            data: { image : 1 },
            async: false,
            success: function(data) {   
                $( "#logger" ).append(data+ '<br />');
            }
        });
        images--;
    }

What this code is doing is processing all the images and then appending the full response, but I want it to append the response for every single image. Somehow the while block is entirely being processed before updating the #logger div. Am I missing something?

4

1 回答 1

2

您必须删除async: false. 这反过来又允许请求完成并在完成时附加。但是,您随后会意识到它们被乱序附加了!为了解决这个问题,我们可以使用 promise 对象和 .then。

images = 10;

var req = $.ajax({
    type: "POST",
    url: "processimage.php",
    data: {
        image: images
    },
    success: function (data) {
        $("#logger").append(data + '<br />');
    }
});
images--;

while (images > 0) {
    req.then(function(){
        return $.ajax({
            type: "POST",
            url: "processimage.php",
            data: {
                image: 1
            },
            success: function (data) {
                $("#logger").append(data + '<br />');
            }
        });
    });
    images--;
}

现在,还有一个可能的问题。如果您需要在images每个请求中传递当前值,前面的代码将在第一个请求之后发送所有请求,最后一个值为images. 为了解决这个问题,我们可以使用 iff。

images = 10;

var req = $.ajax({
    type: "POST",
    url: "processimage.php",
    data: {
        image: 1
    },
    success: function (data) {
        $("#logger").append(data + '<br />');
    }
});
images--;

while (images > 0) {
    (function(i){
        req.then(function(){
            return $.ajax({
                type: "POST",
                url: "processimage.php",
                data: {
                    image: i
                },
                success: function (data) {
                    $("#logger").append(data + '<br />');
                }
            });
        });
    })(images);
    images--;
}

然后您可以通过将选项存储在单独的变量中来使其成为 DRYer,如下所示:

images = 10;

var ajaxOpts = {
    type: "POST",
    url: "processimage.php",
    data: {
        image: 1
    },
    success: function (data) {
        $("#logger").append(data + '<br />');
    }
};

var req = $.ajax(ajaxOpts);
images--;

while (images > 0) {
    (function(i){
        req.then(function(){
            ajaxOpts.data.image = i;
            return $.ajax(ajaxOpts);
        });
    })(images);
    images--;
}
于 2013-11-01T18:52:33.493 回答