简体   繁体   中英

jQuery: How to make an AJAX request and continue without waiting for request to complete?

I want to make an AJAX request "in the background" of my JavasSript function, but my script waits for the AJAX request to complete before it continues to execute my code.

$('div').hide();

$.get('/controller/action', { id: 'abc123' },
    function(data){
        //request completed
        //now update the div with the new data
        $('div').html(data);
    }
);

$('div').slideDown('slow');

//by now hopefully the div has been updated 
//and the user hasn't waited too long

The problem is that the slideDown animation waits to execute until the request has returned a response. How can I get the the animation to execute at the same time as the ajax request?

You code should already be doing the Ajax request "in the background" (asynchronously). The jQuery.get() method is shorthand for:

$.ajax({
  url: url,
  data: data,
  success: success,
  dataType: dataType
});

And the jQuery.ajax() method is async: true by default.

Put the slideDown() in the success callback

$('div').hide();

$.get('/controller/action', { id: 'abc123' },
    function(data){
        alert("Request completed");
        //now update the div with the new data
        $('div').slideDown('slow');
    }
);

Unless you are providing default config for AJAX with async: false ( doc ).

is it possible the the div contains nothing untill the ajax request is complete, and therefore creates the illusion that its waits?

have you tried the good old alert() debugging after the ajax request?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM