How to show waiting message during sync ajax call in browser

前端 未结 2 1129
傲寒
傲寒 2020-12-09 06:49

How to show waiting message on sync ajax call in browser ? I tried code below, turned web server off but \"Saving\" message is not displayed.

After some time only er

相关标签:
2条回答
  • 2020-12-09 07:37

    Your problem is that you're using a synchronous AJAX call and that pretty much locks up the browser until it completes. In particular, the browser won't be able to show your "loading" message before you hit the $.ajax({async:false}) lockup; for example, watch what this does:

    http://jsfiddle.net/ambiguous/xAdk5/

    Notice that the button doesn't even change back to the unclicked visual state while the AJAX is running?

    The solution is to show your loading message, hand control back to the browser, and then lock everything up with your synchronous remote call. One way to do this is to use setTimeout with a delay of zero:

    $('#_info').html(myInfo);
    $('#_info').show();
    setTimeout(function() {
        $.ajax('save', {
            async: false,
            type: 'POST',
            complete: function() {
              $('#_info').hide();
            }
        });
    }, 0);
    

    For example: http://jsfiddle.net/ambiguous/zLnED/

    Some care will be needed of course as this won't be the same inside the setTimeout callback as it was outside but that's easy to take care of.

    Using async:false isn't a very nice thing to be doing to your users though, you should try to avoid it unless it is absolutely necessary (and it rarely is).

    0 讨论(0)
  • 2020-12-09 07:38

    <div class="loading">Loading...</div>

    Your ajax call:

    $('.loading').fadeIn(50, function() {
       $.ajax( 'save',
       {
          async: false,
          type: 'POST'
       } );
    });
    
    $('.loading').fadeOut(50);
    
    0 讨论(0)
提交回复
热议问题