George_Fal 2016-04-01 19:08 采纳率: 0%
浏览 24

每个循环中的jQuery ajax

I have a problem with getting values in success function (ajax) inside the $.each loop.

I've got something like this:

var test = [];
$.each(images, function(index){
    var formData = new FormData();
    formData.append('image', images[index]);

    $.ajax({
        url: 'http://localhost/admin/api/offers/upload_photo',
        data: formData,
        cache: false,
        contentType: false,
        processData: false,
        type: 'POST',
        beforeSend: function(){
            console.log(test.length);               
            test.push(images[index]);       
        },
        success: function(){
            console.log(test.length);
        }
    });
});  

And the output of beforeSend works fine (console log: 0, 1, 2), but another one returns three times 3 (console log: 3, 3, 3). The rest works with no problems, I only struggle with it. Is there anyone who is able to help me? Thanks!

  • 写回答

1条回答 默认 最新

  • weixin_33724570 2016-04-01 19:41
    关注

    AJAX requests are asynchronous by default. This means that it sends the request to the server, but doesn't wait for the response to return before continuing with the code. So the $.each() loop sends all three AJAX requests, and executes all their beforeSend: functions, immediately. The success: functions aren't executed until the responses are processed, which won't be until your code returns to the main browser event loop.

    Since all the beforeSend: functions are executed before any of the responses are processed, the test array will be filled with all the images when the success functions are executed. So they'll all see test.length == 3.

    评论

报告相同问题?