How to use ajaxStart to show loading spinner?

前端 未结 1 1881
-上瘾入骨i
-上瘾入骨i 2021-01-12 10:26

I have a webpage that runs a python script with the command shell_exec. I\'d like for a loading spinner, the \'Please wait while this page loads\' sort of message, to show w

相关标签:
1条回答
  • 2021-01-12 11:05

    Whenever an Ajax request is about to be sent, jQuery checks whether there are any other outstanding Ajax requests. If none are in progress, jQuery triggers the ajaxStart event.

    Have a loading gif image like shown below

               <div id="loading">
                    <img src="loading.gif" />  
               </div>
    

    First hide this loading div(because loading image have to be shown when ajax request is about to sent).

                  <script>
                       var $loading = $('#loading').hide();
                       //Attach the event handler to any element
                       $(document)
                         .ajaxStart(function () {
                            //ajax request went so show the loading image
                             $loading.show();
                         })
                       .ajaxStop(function () {
                           //got response so hide the loading image
                            $loading.hide();
                        });
                  </script>
    

    For more see at jQuery documentation

    Do I need to call ajax to execute the ajaxStart? How would I call it?

    Yes when you triggered a ajax request then only ajaxStart will get triggered automatically.

    For ajax there are multiple ways with jquery, below I am giving with load function.

                   $( ".result" ).load( "some_file.py" );
    

    some_file.py output will inserted into div with class name result.

    To trigger the load event you can use button click or any other as need.

                   $( ".trigger" ).click(function() {
                      $( ".result" ).load( "some_file.py" );
                   });
    
    0 讨论(0)
提交回复
热议问题