简体   繁体   中英

Unexpected javascript function behaviour

What I want is to add a loader bar to my HTML , while my method does some time consuming AJAX calls and DOM manipulation.

The problem is, that show() method won't show the loader bar until the AJAX calls are done, how do I fix this?

I want to force the show() method, then do AJAX calls and DOM stuff, then force the hide() method.

Method doing AJAX calls:

$('.my-button').on('click', function(){
   $('#display-loader').show();
   // ajax and dom manipulation
   $('#display-loader').hide();
});

EDIT: Seems like there's some misunderstanding as to what my problem is. If I change my code to this:

$('.my-button').on('click', function(){
   $('#display-loader').show();
   // ajax and dom manipulation
});

It still won't SHOW the loader bar, untill the AJAX methods are done, it's like it skips the show() method, does AJAX stuff, and then calls the show() afterwards.

All the AJAX calls have async set to false . I have 5 AJAX calls, and each AJAX call relies on the data fetched from the previous call, I have no way to set the async to true , is there a way to get around this, and force the DOM to display the image, and then do AJAX calls?

You need to call hideLoader() within AJAX success function, to hide after ajax operation. As AJAX is asynchronous, so in your code hideLoader() execute before finish ajax call and done dom stuff.

$('.my-button').on('click', function(){
   showLoader();
   $.ajax({
     ....
     success: function() {
          hideLoader();
     } 
   });
});

according to @Esailija comment to hide after complete callback do like:

$('.my-button').on('click', function(){
   showLoader();
   $.ajax({
     ....,
     success: function(){

     },
     complete: function() {
         hideLoader();
     }
   })
});

you can do next:

showLoader();
$.ajax({
   type : 'POST',
   url : url,
   data : postData,
   success : function (returnData) {

   },
   error : function (xhr, textStatus, errorThrown) {

   },
   complete : function (){
       hideLoader();
   }
});

I recommend maybe the following way:

$.ajax({
  .....
}).done(function () {
  hideLoader();
});

This will insure the loader goes away. If your ajax isn't successful then the success callback will never be reached and then the loader will stay on the page.

But it depends on the scenario. You can also just put it in your error callback.

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