简体   繁体   中英

jQuery. obtain var from ajax in cycle

for (var i = 0; i < 3; i++){
    $.ajax({
        url: "ajax.php",
        success: function(data){
            alert(i);
        }
    });
}

I need a solution to get alerts with "0", "1" and "2". Аt this time of course I see 3 alerts with "3".

You need to put a closure around your $.ajax() call.

for (var i = 0; i < 3; i++){
    (function (loop_var) {
        $.ajax({
            url: "ajax.php",
            success: function(data){
                alert(loop_var);
            }
        });
    })(i);
}

Currently it is outputting 3 as my the time the Ajax returns the value of i is indeed 3 .

Use an anonymous function wrapper around the code to create a closure that will keep the value until the asynchronous response arrives:

for (var i = 0; i < 3; i++){

  (function(i){

    $.ajax({
      url: "ajax.php",
      success: function(data){
        alert(i);
      }
    });

  })(i);

}

Pass the i value to the ajax.php page as a parameter. The ajax.php page has to return i to the calling page. So let the ajax.php page return i. You can use json objects or a trivial pipe-separated string to store returning values from ajax.php.

for (var i = 0; i < 3; i++){
    $.ajax({
        data: {par: i},
        url: "ajax.php",
        success: function(data){
            //data is a pipe-separated string
            var cnt = data.split("|")[0];
            alert(cnt);
        }
    });
}

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