简体   繁体   中英

ajax .done not running properly, seems to skip code

I have the code bellow running in a .each function. However when all is set and done and i do alert(inserted); or alert of any other variable they come out 0 which is what i have them set as when i declare them. I am sure they are within scope. I have a feeling this has to do with the timing of the ajax because if i put an alert after each call, the counter system works. Any thought? Also I am sure that the proper if statements are called as I attached alerts (as i said above which when i do this the counter works) and they fire properly AND no error codes as brought up from the consol.

$.ajax({
    type: "POST",
    url: "/php/filename.php",
    data: {
        one: $('#1').val(),
        two: $('#2').val(),
        three: $('#3').val(),
        four: $('#4').val(),
        five: $('#5').val(),
        six: $('#6').val(),
        seven: $('#classlist').val(),
        id: $('#7').html()
    }
}).done(function(msg) {
    if (msg == "inserted") {
        inserted++;
    }
    else if (msg == "updated") {
        updated++;
    }
    else if (msg == "duplicate") {
        duplicate++;
    }
    else if (msg == "0") {
        fail++;
    }
});

Ajax is asynchronous, your alert is happening before the ajax is complete. Store all of your ajax return values in an array, pass them all to .when, and then use it's done to alert the value of your variable.

var promiseArr = [], inserted = 0;

for (var i = 0; i < 30000; i++) { // <--- unrealistic number of iterations
    promiseArr.push($.ajax({url:"foo.php?id=" + i}).done(function(){
        inserted++;
    }));
}
$.when.apply($,promiseArr).done(function(){
    alert(inserted);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM