循环遍历数组,每次都进行ajax调用,不起作用
我遇到这个问题,基本上,我有一个大数组,每次循环时我都会将其分解为较小的数组。在循环中,我有一个 ajax 调用,它将该数组发送到一个 url。问题是它只进行一次 ajax 调用,但它会在控制台中记录其他较小的数组。知道为什么会发生这种情况吗?
//emailArray = [[email protected], [email protected]..... (up to a number greater than 10)
while(emailArray.length) {
console.log(emailArray.splice(0,10));
$.ajax({
url:"some/url",
type: "POST",
data: {
"object": emailArray.splice(0,10)
},
dataType: "json",
success: function (data, status, xhr) {
//callback(data);
console.log('data from success');
console.log(data);
}
});
console.log('after ajax');
}
编辑,循环旨在为大数组中的每 10 个项目发送一个新的 ajax 请求,并且发送的数组中有 10 个项目。当我将它们记录在控制台中时,.splice 很好地分解了数组......但它没有执行 ajax 部分
I'm having this problem, where basically, I have a big array, that I break down to smaller arrays each time the loop does a loop. Within the loop I have an ajax call which sends that array to a url. The problem is that it only makes the ajax call once, but it logs the other smaller arrays in the console. Any idea why this is happening?
//emailArray = [[email protected], [email protected]..... (up to a number greater than 10)
while(emailArray.length) {
console.log(emailArray.splice(0,10));
$.ajax({
url:"some/url",
type: "POST",
data: {
"object": emailArray.splice(0,10)
},
dataType: "json",
success: function (data, status, xhr) {
//callback(data);
console.log('data from success');
console.log(data);
}
});
console.log('after ajax');
}
Edit, the loop is designed to send a new ajax request for every 10 items in the big array, and the array that is sent has 10 items in it. The .splice breaks up the arrays fine when I just log them in the console... but it's not doing the ajax part
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
.splice()
对源数组具有破坏性,因此您的console.log(emailArray.splice(0,10));
会弄乱 emailArray 并导致您错过迭代。您可以在
console.log().slice()
(这不是破坏性的,但会返回副本)而不是.splice()
代码> 语句如下:.splice()
is destructive on the source array so yourconsole.log(emailArray.splice(0,10));
is messing up emailArray and causing you to miss iterations.You can use
.slice()
(which is not destructive, but returns a copy) instead of.splice()
in theconsole.log()
statement like this: