带有FOR循环JS的AJAX [重复]

This question already has answers here:
                </div>
            </div>
                    <div class="grid--cell mb0 mt4">
                        <a href="/questions/750486/javascript-closure-inside-loops-simple-practical-example" dir="ltr">JavaScript closure inside loops – simple practical example</a>
                            <span class="question-originals-answer-count">
                                (44 answers)
                            </span>
                    </div>
            <div class="grid--cell mb0 mt8">Closed <span title="2015-10-28 14:53:12Z" class="relativetime">4 years ago</span>.</div>
        </div>
    </aside>

I have a problem with using AJAX and FOR loop. In PHP file is a few if which dependly of number (1-9) returns echo with a price.

f.ex.

1 -> echo "15.20";
2 -> echo "11.10";
3 -> echo "13.65";
4 -> echo "14.30";

JS Script:

for(i=1; i<10; i++)
{
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            document.getElementsByClassName("courierprice")[i-1].innerHTML = xmlhttp.responseText;
        }
        else
        {
            document.getElementsByClassName("courierprice")[i-1].innerHTML = "shit";
        }
    }
    xmlhttp.open("GET", "gethint.php?q=" + i , true);
    xmlhttp.send();
}

When there is no loop, and just a var i = 1, it returns correctly (15.20), but if I want to do it couple of times, I just got in all classes "shit".

If you got any advice how to do it, please let me know. Thanks!

</div>

You should wrap your whole loop content in a function and pass the i there.

for(i=1; i<10; i++) {
        (function (i) {

            ...your async code...

        })(i);
}