gpt4 book ai didi

javascript - 等待 AJAX 请求完成?

转载 作者:搜寻专家 更新时间:2023-11-01 04:46:51 26 4
gpt4 key购买 nike

我现在有个问题让我很困惑。我正在使用 ajax 从网站获取一些 ID。完成后,我想将 ID 存储在一个变量中以供进一步处理。我的代码布局如下:

var ids;

function get_ids() { ... Get the ID's from the site and store them in the global variable ids ... }

get_ids();
alert(ids.length);

如您所见,ids 将始终为 0,因为脚本将在 get_ids 中的 ajax 请求有机会响应之前继续运行。

我想做的事情最好的方法是什么?我想等到 get_ids 完成。

最佳答案

您需要让 get_ids 接受一个回调参数,并在收到响应时调用它。

例如:

function get_ids(callback) {
...
response: function(data) {
...
callback(data);
}
...
}

get_ids(function(ids) {
...
});

关于javascript - 等待 AJAX 请求完成?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5747898/

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