开发者

Pausing the user while an ajax call takes place

I have a few buttons on a page, which when clicked, trigger an ajax call, which then accesses the DB.

After a click, I want the user to not be able to click any of the buttons until the ajax call responses.

But, if possible, I'd like the user to get some indication that the system is in proccess so he won't think it's stuck.

Some sort of a simple animation and graying out the page can do the trick, until there's a response.

Also, I'd like to set a time limit on the ajax call so i开发者_JAVA百科f there's no response for, say, 10 seconds, the call will return and give an error message.

What are my options?

I'm working under WordPress, so if it has some nice way to deal with this that's also an option.


this should do it

js

$('#overlay').show();

$.ajax({
   url: 'somepage.htm',
   timeout: 10000, /*milliseconds*/
   })
  .complete(function(){ $('#overlay').hide(); }) /*runs after success or error*/
  .success(function(data){ /*do whatever*/ })
  .error(function(){ /*timeout or general error*/ });

html

<div id="overlay"></div>

css

#overlay{
  display:none;
  position:fixed;
  top:0;
  left:0;
  right:0;
  bottom:0;
  background-color:#666;
  opacity:0.6;
  z-index:999;
}

demo at http://jsfiddle.net/gaby/X6sDS/1/


With jQuery you can handle ajax events globally, check out http://api.jquery.com/category/ajax/global-ajax-event-handlers/

// #loading can be your loading element
$("#loading").ajaxStart(function(){

    // show your loading element
    $(this).show();


    // disable all buttons with a specific class
    $('.my_ajax_btns').attr('disabled', true);
});

$("#loading").ajaxStop(function(){

    // hide loading
    $(this).hide();


    // enable back your buttons
    $('.my_ajax_btns').attr('disabled', false);
});


Try this Jquery plugin to block the user before AJAX call response comes. You can set the timeout in milliseconds in AJAX settings.

http://jquery.malsup.com/block/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜