gpt4 book ai didi

javascript - jQuery连续ajax调用

转载 作者:行者123 更新时间:2023-12-03 10:05:27 25 4
gpt4 key购买 nike

我正在尝试使用 JavaScript 从网站的选择选项中获取数据。目的是从拥有我国区域的网站上获取这些区域的列表。

我的问题如下:该列表按 3 个选择分层显示,其中第一个选择具有加载的第一级区域列表,我可以很好地获取该列表,但是当我 $.each 第二个列表,通过调用网站使用的ajax请求,并带有当前顶级区域的标志,所有子区域都分配给最后一个顶级区域。看起来整个脚本并没有等待 ajax 调用,因此当它们调用时,当前 ID 是顶级列表中的最后一个。我该如何解决这个问题?例如,是否可以在 done() 回调中访问请求中发送的data

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

最佳答案

发生这种情况是因为所有迭代都发生在第一个 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()

关于javascript - jQuery连续ajax调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30379736/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com