最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Waiting for AJAX request to finish? - Stack Overflow

programmeradmin0浏览0评论

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:

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.

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

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:

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.

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

Share Improve this question asked Apr 21, 2011 at 17:53 Riess HowderRiess Howder 4052 gold badges7 silver badges14 bronze badges 0
Add a comment  | 

4 Answers 4

Reset to default 11

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

For example:

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

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

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:

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

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

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

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

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.

See Synchronous AJAX

发布评论

评论列表(0)

  1. 暂无评论