开发者

jQuery For Loop with Post Not Counting Correctly

So, I have the following line of code, that does a for loop and subjects 12 on every loop. If I alert right before the post, it alerts the numbers as you would expect (72, 60, 48, 36, 24). But, with the alert inside the post it alerts the number 12 five times. Any idea why that is? Any idea where the number 12 is coming from?

function loadEstimates(option){
    for(term_length=72; term_length>=24; term_length-=12){
        var post_options = {loadEstimates: 'true', coverage_option:option, term_length:term_length};
        $.post('../includes/process.php', post_options, function(response, status){
            alert(term_length);
        });
    }
}

The second part of the question is, I want to output these in order and I've noticed on occasion the post will output something random like 36, 48, 24, 72, 60 because of server response times. How can I put the 'response' from the post into an array or something that will let me sort it before displaying it?

Thanks!!

/////// EDIT //////// Okay, so I took some of ChessWhiz's advice and used an array and came up with.

function loadEstimates(option){
    var term_length = new Array('72','60','48','36','24');
    var term_length_output = new Array(5);
    $.each(term_length, function(index, t_length){
        var post_options = {loadEstimates: 'true', coverage_option:option, term_length:t_length};
        $.post('../includes/process_instantquote.php', post_options, function(response, status){
            term_length_output[t_length] = response;
        });
    });

    alert(term_length_output);
}

This also solves my potential future conundrum of if I decide to use a number in the term_length that isn't divisible by 12. But, the term_length_output开发者_JAVA百科 is still blank. Any idea what I am doing wrong with that?


** FINAL EDIT *****

Here is the code I ended up using. It does exactly what I need it to do. It's probably not the most 100% correct way, but it works.

Thank you all very much for your answers and help!!!

function loadPriceEstimates(option){
    $('#package-term-options table tbody').append('<tr><td style="text-align:center;" colspan="5"><img src="images/ajax-loader-small.gif" alt="Loading..." class="small-loading"/></td></tr>').show();
    var term_length = new Array('72','60','48','36','24');
    var term_length_output = new Array();
    var count = 0;
    $.each(term_length, function(index, t_length){
        var post_options = {loadPriceEstimates: 'true', coverage_option:option, term_length:t_length};
        $.post('../includes/process_instantquote.php', post_options, function(response, status){
            if(status == 'success'){
                term_length_output[t_length] = response;
                count++;
                if(count == 5){
                    term_length_output.sort();
                    term_length_output.reverse();
                    $('#package-term-options table tbody').html('');
                    $.each(term_length_output, function(index, value){
                        $('#package-term-options table tbody').append(value);
                    });
                }
            }
        });
    });
}


I think that's because the for loop body is not a scope for the callback function closure, the scope is the container function.

Try this:

function loadEstimates(option){
    for(term_length=72; term_length>=24; term_length-=12){
        postProcess(term_length);
    }
}

function postProcess(term_length) {
        var post_options = {loadEstimates: 'true', coverage_option:option, term_length:term_length};
        $.post('../includes/process.php', post_options, function(response, status){
            alert(term_length);
        });
}

For more info see:

  • http://www.mennovanslooten.nl/blog/post/62
  • http://www.javascriptkit.com/javatutors/closures.shtml
  • http://en.wikipedia.org/wiki/Closure_%28computer_science%29


Using an index variable that counts backwards by 24's is prone to error. Instead, use a normal index, then calculate the term_length. Next, you can use an array to store the results. However, if the callback hasn't completed running, the array won't yet hold all the results. Lastly, you need to make a copy of the loop variable to escape the closure. Example:

function loadEstimates(option) {
    for(i = 0; i < 5; i++) {
        var resultsIndex = i;
        var term_length = 72 - (i * 12);
        var post_options = {loadEstimates: 'true', coverage_option:option, term_length:term_length};

        $.post('../includes/process.php', post_options, function(response, status){
            results[resultsIndex] = response;
        });
    }
}

Then, your results will be nicely aligned in the results array. The [12, 12, 12, 12, 12] side-effect caused by closure is basically caused because the last value of term_length is getting outputted every time, which is 24 - 12 = 12, due to the way the for loop modifies it and the function closes over it.


The problem has to do with the way for works: it uses the same variable throughout its lifespan (rather than instantiating new ones), meaning that same variable is being bound to your $.post() callback every time. AJAX calls are asynchronous, and that callback isn't being called until after your loop has finished and term_length has made its way down to 12.

For a discussion of the general problem outside of JavaScript, see "Python's lambda is broken!"

The solution, then, is to, somehow or another, get JavaScript to instantiate a new variable every iteration so it's not changed out from under you during the looping. One way to do that is to pass it through a function. See Nicolas Bottarini's answer for the code.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜