Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
315 views
in Technique[技术] by (71.8m points)

javascript - How to show waiting message during sync ajax call in browser

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 error event from ajax call occurs, without any progress message.

How to show waiting message to user if sync ajax call is in progress ?

var myInfo = '<div class="ui-state-highlight ui-corner-all" style="position: fixed;' +
    'z-index: 10000; margin-top: 2%; margin-left: 2%">' +
    ' <br />' +
    '&nbsp;<span class="ui-icon ui-icon-info" style="float: left; margin-right: .3em;"></span>' +
    '<strong>Saving</strong>&nbsp;<br />' +
    '<br /></div>'
$('#_info').html(myInfo);
$('#_info').show();

$.ajax( 'save',
   {
       async: false,
       type: 'POST'
    } );
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...