weixin_33726943 2015-05-21 16:46 采纳率: 0%
浏览 46

jQuery连续Ajax调用

I am trying to fetch data from select options from a website with javascript. The purpose is to get a list of zones in my country from a website that has them.

My problem is as follows : The list is displayed hieraquically in 3 selects, where the first one has a loaded list of the first level zones which I can get just fine, but then when I $.each the second list by calling the ajax request used by the website with a flag of the current top level zone, all the subzones are assigned to the last top zone. It seems like the overall script is not waiting for the ajax calls to be made, so when they get made the current ID is the last one on the top level list. How can I go around this? Is it possible for example to access the data sent in the request within the done() callback?

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条回答 默认 最新

  • csdn产品小助手 2015-05-21 17:05
    关注

    It happens because all the iterations happen before your first ajax call returns. It's like this:

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

    You can use closures to pass data, see this: Passing variables to $.ajax().done()

    评论

报告相同问题?

悬赏问题

  • ¥50 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥200 uniapp长期运行卡死问题解决
  • ¥15 latex怎么处理论文引理引用参考文献
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?