AJAX call in for loop won't return values to correct array positions

后端 未结 2 925
被撕碎了的回忆
被撕碎了的回忆 2020-12-08 03:32

I need to get a range of pages using AJAX and put them into an array, where their given place in the array is equal to the i of a for loop (it\'s a caching-like

2条回答
  •  广开言路
    2020-12-08 03:47

    You need a closure:

    var bongo = [];
    for (i = 0; i < 10; i++)
    {
    
      (function(i)
        {
          jQuery.ajax(
            {
              type: "GET",
              url: "http://localhost",
              data: queryString,
              success: function(request) { bongo[i] = request } 
            });  
        })(i);
    }
    

    Loops are the #1 place where inline functions stump people. The bongo[i] = result isn't called until later. The value of i at that time is different (most likely 11). If you want to "trap" or "capture" the current value of i, you need to create a new scope. The only way to do that in javascript is with another function.

提交回复
热议问题