jQuery连续的ajax调用

时间:2015-05-21 16:46:05

标签: javascript jquery ajax

我正在尝试使用javascript从网站的选择选项中获取数据。目的是从拥有它们的网站获取我所在国家/地区的区域列表。

我的问题如下:列表在3个选项中以层次结构显示,其中第一个列表包含第一级区域的加载列表,我可以得到很好,但是当我$.each第二个列表时通过使用当前顶级区域的标志调用网站使用的ajax请求,将所有子区域分配给最后一个顶部区域。似乎整个脚本没有等待进行ajax调用,因此当它们生成时,当前ID是顶级列表中的最后一个。我怎么能绕过这个?例如,是否可以在data回调中访问请求中发送的done()

var current_d = 0;
var zones = {
  d : [],
  c : [],
  f : []
}; 

$.each($('#ddState>option:gt(0)'), function(i, v) {
    zones.d.push({name : $.trim($(v).html()), id : parseInt($(v).attr('value'))});
    current_d = parseInt($(v).attr('value'));

    var data = {};
    data.Action = '***';
    data.ID = current_d; // This is the ID flag for the ajax request

    $.ajax({
        type: 'POST',
        url: '***',
        data: data,
        cache: false,
        dataType: 'json'
    })
    .done(function(response) {
    $.each(response, function(i, v) {
        zones.c.push({name : v.Name, id : parseInt(v.Id), parent_id : current_d});
        console.log(current_d); // When it gets here the flag has changed to the last ID in the previous list
    });
});

1 个答案:

答案 0 :(得分:1)

这是因为所有迭代都发生在您的第一个ajax调用返回之前。就像这样:

for x=1 to 10
  current_d=x
  do something
next x
console.log(current_id); //Why is current_d=10 here?

您可以使用闭包传递数据,请参阅:Passing variables to $.ajax().done()