jQuery modal dialog on ajaxStart event

2019-04-09 15:43发布

问题:

I'm trying to use a jQuery UI modal dialog as a loading indicator via the ajaxStart, ajaxStop / ajaxComplete events. When the page fires, an Ajax handler loads some data, and the modal dialog shows just fine. However, it never hides or closes the dialog when the Ajax event is complete. It's a very small bit of code from the local server that is returned, so the actual Ajax event is very quick.

Here's my actual code for the modal div:

      $("#modalwindow").dialog({
              modal: true,
              height: 50,
              width: 200,
              zIndex: 999,
              resizable: false,
              title: "Please wait..."
      })
      .bind("ajaxStart", function(){ $(this).show(); })
      .bind("ajaxStop", function(){ $(this).hide(); });

The Ajax event is just a plain vanilla $.ajax({}) GET method call.

Based on some searching here and Google, I've tried altering the ajaxStop handler to use $("#modalwindow").close(), $("#modalwindow").destroy(), etc. (#modalwindow referred to here as to give explicit context).

I've also tried using the standard $("#modalwindow").dialog({}).ajaxStart(... as well.

Should I be binding the events to a different object? Or calling them from within the $.ajax() complete event?

I should mention, I'm testing on the latest IE8, FF 3.6 and Chrome. All have the same / similar effect.

回答1:

Found the answer:

  $("#modalwindow").dialog({
          modal: true,
          height: 50,
          width: 200,
          zIndex: 999,
          resizable: false,
          title: "Please wait..."
  })
  .bind("ajaxStart", function(){
      $(this).dialog("open"); })
  .bind("ajaxStop", function(){
      $(this).dialog("close");
  });

Note to self: RTFM.

Of course in all this, now I realize that it opens and closes so quickly as to be useless. Oh well, hopefully someone will find this helpful.



回答2:

"Whenever an Ajax request completes, jQuery checks whether there are any other outstanding Ajax requests." Do you have other AJAX requests running at the same time? You'll want to use ajaxComplete or a callback option to .ajax() instead, to just get the one completion.