looping through an array, and making an ajax call each time, not working
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 = [email1@something.com, email2@something.com..... (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
.splice()
is destructive on the source array so your console.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 the console.log()
statement like this:
//emailArray = [email1@something.com, email2@something.com..... (up to a number greater than 10)
while(emailArray.length) {
console.log(emailArray.slice(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');
}
精彩评论