模式对话框中的Ajax Spinner

I am trying to display the ajax spinner in modal dialog. I have an ajax spinner already in my page in one of the ajax action for which initially I have coded it using the following code.

$(document)
      .ajaxStart(function () {
              $loading.show();
      })
      .ajaxStop(function () {
              $loading.hide();
});

But this is too generic, now I want to show the spinner in one of the modal popup and I tried using the following code

$('#modal_loading_div').bind("ajaxStart", function(){
  alert('In ajax Start of modal dialog');
  $modalLoading.show();
});
$('#modal_loading_div').bind("ajaxStop", function(){
  alert('In ajax Stop of modal dialog');
  $modalLoading.hide();
});   

The above code is not called single time and control is not flowing. As an immediate tweak I tried my way doing this

$(document)
      .ajaxStart(function () {
          if(dialog){
              $('#delete_loading_div').show();  
          }else{
              $loading.show();
          }
      })
      .ajaxStop(function () {
          if(dialog){
              $('#delete_loading_div').hide();  
          }else{
              $loading.hide();
          }
});

but want to know the right way to do this. I am using the jquery-2.1.4

There's not really a 'correct' way of doing this.

As of jQuery 1.8, the .ajaxStart() method should only be attached to document. (https://api.jquery.com/ajaxStart/)

If you're binding on ajaxStart, then the code you've shared is really the only way of differentiating between whether the 'modal' or 'general' spinner should show. I imagine you have something like:

$('.open-modal-dlg').click(function(){
    dialog = true;
    $.ajax(...);
    ...
});
$('.close-modal-dlg').click(function(){
    dialog = false;
    ...
});

That's fine, as it is.

The only alternative I can see is to not use $.ajaxStart, and instead handle displaying the spinner on each of your AJAX calls.

$('.loading').show();
$.ajax(...).always(function(){
    $('.loading').hide();
});

// -- for modals...

$('.loading-modal').show();
$.ajax(...).always(function(){
    $('.loading-modal').hide();
});

.ajaxStart is a global AJAX jQuery event, so there's no way of limiting it, apart from keeping track of a separate variable yourself.