讓AJAX運行中跳出Loading

讓使用者點擊按鈕後可以知道程式正在運行

也能避免使用者重複一直點的問題

CSS部分

<style>
    div.loadingdiv {
        height: 100%;
        width: 100%;
        /*100%覆蓋網頁內容, 避免user在loading時進行其他操作*/
        position: fixed;
        z-index: 99999;
        /*須大於網頁內容*/
        top: 0;
        left: 0;
        display: block;
        background: #000;
        opacity: 0.6;
        text-align: center;
    }

    div.loadingdiv img {
        position: relative;
        vertical-align: middle;
        text-align: center;
        margin: 0 auto;
        margin-top: 50vh;
    }

    
</style>

HTML中加入此段 img 為隨便一個gif檔
div 的display = none 一開始設為隱藏

 <div class="loadingdiv" id="loading" style="display: none">
        <img src="~/gif/load.gif" />     
 </div>

AJAX部分

$.ajax({
          beforeSend: function () {
             //將div顯示
             $('#loading').css("display", "");
          },
          type: 'GET',
          async: false,
          url: 自己的url,
          success: function (data) {
               //do something
          },
          complete: function () {
              //再次隱藏
              $('#loading').css("display", "none"); 
              
              //測試可利用setTimeout 讓loading效果明顯
              //setTimeout(function () { $('#loading').css("display", "none"); }, 3000);
              
          }
       
      })