1

I don't know , its a bug or not. see my examples :

for(i=0;i<2;i++){
  $.ajax({
    url : 'process.php',
    type: "POST",
    data : "abcd",
    success : function(data){
      alert(i);
    }
  })
}

or

for(i=0;i<2;i++){
  $.post("process.php",{dataw:"abcd"},function(data){
    alert(i);
  })
}

why output is 2 ?

AliN11
  • 2,387
  • 1
  • 25
  • 40

1 Answers1

0

i won't keep its value, it'll loop through and stay at the last value (2).

You can wrap your value in a function instead.

for (i = 0; i < 2; i++) {
    $.ajax({
        url: 'process.php',
        type: "POST",
        data: "abcd",
        success: function(value) {
            return function(data) {
                alert(value);
            }
        }(i)
    })
}

Same thing for post:

for (i = 0; i < 2; i++) {
    $.post("process.php", {
            dataw: "abcd"
        },
        function(value) {
            return function(data) {
                alert(value);
            }
        }(i)
    );
}
Dave Chen
  • 10,887
  • 8
  • 39
  • 67