【发布时间】:2016-07-21 17:11:13
【问题描述】:
我在 $.each 循环内获取成功函数 (ajax) 中的值时遇到问题。
我有这样的东西:
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);
}
});
});
并且 beforeSend 的输出工作正常(控制台日志:0、1、2),但另一个返回三倍 3(控制台日志:3、3、3)。其余的工作没有问题,我只是在努力。有谁能帮助我吗?谢谢!
【问题讨论】:
-
似乎它正在做它应该做的事情。
-
您的
each循环似乎在任何success函数触发之前完成。因此,当success触发其中一次迭代时,循环已经完成,test的长度为三。这可能会提供信息:How do I return the response from an asynchronous call? -
这就是为什么 ajax 是异步的 :) 顾名思义 :)
-
这种行为似乎合乎逻辑且符合预期。你想让代码做什么?