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.

    评论

报告相同问题?

悬赏问题

  • ¥15 python变量和列表之间的相互影响
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)