AJAX调用的循环将不会返回值来校正阵列位置阵列、返回值、位置、AJAX

2023-09-10 16:02:13 作者:日落人海

我需要获得一系列的使用AJAX页面,并把它们放到一个数组,数组中的给定的位置等于的我循环(这是一个缓存类功能博客页面,for循环的范围是完全可变的)。我在做一个类似于以下内容:

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 function for blog pages, and the range of the for loop is entirely variable). I'm doing something akin to the following:

var bongo = new Array();

for (i = 0; i < 10; i++) {

    jQuery.ajax({ type: "GET", url: http://localhost, data: queryString, success: function(request) { bongo[i] = request } })

}

现在的问题是,除非我补充异步:假到阿贾克斯选项(这会使它... SJAX?),这​​将导致请求基本暂停浏览器,逆着我想要做的,在成功回调,我将总是最终成为11,当然,而我希望它返回的数据倒入从0阵列10的每个槽

The problem is, that unless I add async: false to the .ajax options (which would make it... SJAX?), which causes the requests to basically pause the browser, going against what I'm trying to do, the i in the success callback will always end up being 11, whereas I of course want it to pour the returned data into each slot of the array from 0 to 10.

我试过这个替换该行:

bongo[i] = jQuery.ajax({ type: "GET", url: http://localhost, data: queryString }).responseText

但是,这并没有区别。

But that made no difference.

推荐答案

您需要关闭:

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);
}

循环是排名第一的地方,内联函数难倒人。该邦戈[I] =结果不叫,直到后来。 当时的价值是不同的(最有可能的11)。如果你想陷阱或捕获的电流的值,你需要创建一个新的作用域。要做到这一点在JavaScript的唯一方法是使用其他功能。

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.