javascript 等待 AJAX 请求完成?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5747898/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 18:11:19  来源:igfitidea点击:

Waiting for AJAX request to finish?

javascript

提问by Riess Howder

I have a problem that is confusing me at the moment. I am using ajax to get some ID's from a website. Once it's complete I want to store the ID's in a variable for further processing. I have my code laid out like this:

我有一个问题,目前让我感到困惑。我正在使用 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);

As you can see ids will always be 0 because the script will continue to run before the ajax request in get_ids has had a chance to respond.

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

What's the best way to what I'm trying to do? I want to wait until get_ids has finished.

我正在尝试做的最好的方法是什么?我想等到 get_ids 完成。

回答by SLaks

You need to make get_idstake a callback parameter and call it when it receives a response.

您需要get_ids获取一个回调参数并在收到响应时调用它。

For example:

例如:

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

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

回答by David Fullerton

It depends on your AJAX framework, but pretty much any framework will allow you to specify a function to run when the AJAX request is complete. In JQuery:

这取决于您的 AJAX 框架,但几乎任何框架都允许您指定在 AJAX 请求完成时运行的函数。在 JQuery 中:

function get_ids_complete() {
    alert(ids.length);
}

function get_ids() {
    $.get('/ids', function (data) {
        // do something with the data
        get_ids_complete();
    });
}

回答by Munzilla

If you're using plain old javasript, you can call a function to run after the AJAX has completed like so:

如果您使用的是普通的旧 javasript,您可以调用一个函数在 AJAX 完成后运行,如下所示:

ajaxCall.onreadystatechange=function()
  {
  if (ajaxCall.readyState==4 && ajaxCall.status==200)
    {
     //do your ID stuff here
    }
  }

回答by user1032402

I'm using synchronous AJAX in situations like that; it's a blocking call, which I ordinarily avoid, but I don't see an alternative.

我在这种情况下使用同步 AJAX;这是一个阻塞调用,我通常会避免,但我没有看到替代方法。

See Synchronous AJAX

请参阅同步 AJAX