Show Spinner When Teble Row Click

2019-06-09 00:06发布

问题:

I have an a table. When i clicked the table rows , after that ajax request functions are called and then more than one tables load. I want to show spinner while ajax methods run. So that i write code like as below.

$(".table-row").click(function (evt) {
   ShowSpinnerFuntion();
   var $cell = $(evt.target).closest('td'), msg;
   var id = $cell.attr("id");
   CallAjaxMethodForTable1(id);
   CallAjaxMethodForTable2(id);
   CallAjaxMethodForTable3(id);
   CallAjaxMethodForTable4(id);
});

When i execute this click function, spinner is shown after all tables are load with ajax requests. Namely ajax methods run before "ShowSpinnerFuntion()" method although i call method (show spinner) first.

I write only show spinner function in this click function method.Like as:

$(".table-row").click(function (evt) {
   ShowSpinnerFuntion();
   var $cell = $(evt.target).closest('td'), msg;
   var id = $cell.attr("id");
   //CallAjaxMethodForTable1(id);
   //CallAjaxMethodForTable2(id);
   //CallAjaxMethodForTable3(id);
   //CallAjaxMethodForTable4(id);
});

When i execute click function like as above, after that spinner is shown directly. How can i execute spinner function before ajax request functions. How can i give priority to this javascript functions.

回答1:

Just call required ajax functions in your row click function

$(".table-row").click(function (evt) {
   var $cell = $(evt.target).closest('td'), msg;
   var id = $cell.attr("id");
   CallAjaxMethodForTable1(id);
   CallAjaxMethodForTable2(id);
   CallAjaxMethodForTable3(id);
   CallAjaxMethodForTable4(id);
});

Then define the functions as below. In the beginning show the loader and on success or error hide the loader.

function CallAjaxMethodForTable1(){
$('.loaderImage').show();
$.ajax({
        type: "POST",
        url: "/some_url",
        data: { id: id },                        
        success: function(data){                
            $('.loaderImage').hide();
        },
        error: function (response) {
           $(".loaderImage").hide();

       }           
    });
}


回答2:

I hope it's work

$(".table-row").click(function (evt) {
$('.loaderImage').show();
   var $cell = $(evt.target).closest('td'), msg;
   var id = $cell.attr("id");
   CallAjaxMethodForTable1(id);
   CallAjaxMethodForTable2(id);
   CallAjaxMethodForTable3(id);
   CallAjaxMethodForTable4(id);
});



function CallAjaxMethodForTable4(){
$.ajax({
        type: "POST",
        url: "/some_url",
        data: { id: id },                        
        success: function(data){                
            $('.loaderImage').hide();
        },
        error: function (response) {
           $(".loaderImage").hide();

       }           
    });
}

and also mention this code in every method

 error: function (response) {
               $(".loaderImage").hide();

           }