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

javascript - jQuery: How to make an AJAX request and continue without waiting for request to complete? - Stack Overflow

programmeradmin6浏览0评论

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

$('div').hide();

$.get('/controller/action', { id: 'abc123' },
    function(data){
        //request pleted
        //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?

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

$('div').hide();

$.get('/controller/action', { id: 'abc123' },
    function(data){
        //request pleted
        //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?

Share Improve this question edited Sep 24, 2010 at 4:31 Andrew asked Sep 23, 2010 at 23:32 AndrewAndrew 239k195 gold badges530 silver badges718 bronze badges 2
  • Hmm. Where is the code that you want to execute? It is inside the "Request pleted" function? Or is it after $('div').slideDown('slow'); ? – DashK Commented Sep 24, 2010 at 0:06
  • 1 Your code works... jsfiddle/pgG9J – chriszero Commented Sep 24, 2010 at 9:03
Add a ment  | 

3 Answers 3

Reset to default 5

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 pleted");
        //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 plete, and therefore creates the illusion that its waits?

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

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论