如何使用jQuery註冊一個在所有Ajax請求完成後呼叫的處理程式?


在本教程中,我們將學習如何使用jQuery註冊一個在所有Ajax請求完成後呼叫的處理程式。Ajax請求通常是瀏覽器為不同任務(例如GET、POST等)呼叫的HTTP請求。因此,當任務執行完畢時,我們可以使用jQuery的ajaxStop()函式註冊一個處理程式。

語法

使用以下語法在ajax請求後註冊處理程式:

$(document).ajaxStop(function () {
   console.log('Registered handler.')
})

說明 - 假設我們在API上有一個GET請求。當API返回結果時,jQuery會檢查是否有任何請求正在等待。如果沒有,則jQuery會觸發ajaxStop()函式。

注意 - ajaxStop()函式必須始終附加到文件

示例1

在下面的示例中,我們透過使用ajaxStop()註冊處理程式,將結果列印到螢幕上以顯示請求已完成。

<!DOCTYPE html>
<html>
<head>
   <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
   <title>TutorialsPoint | jQuery</title>
</head>
<body>
   <center>
      <h1>jQuery ajaxStop() Method</h1>
      <strong>Registers a handler to be called when all Ajax requests have been completed.</strong>
      <br />
      <br />
      <button id="loadBtn">Load page</button>
      <div id="tutorials"></div>
      <div id="loaded"></div>
   </center>
   <script>
      $(document).ajaxStop(function () {
         console.log('Triggered ajaxStop handler.')
         $('#loaded').text('The AJAX request have been completed.')
      })
      $('#loadBtn').click(function () {
         $('#tutorials').load(
            'https://tutorialspoint.tw/javascript/index.htm',
         )
      })
   </script>
</body>
</html>

示例2

在下面的示例中,我們在網頁上方有一個載入螢幕,在請求完成後將其移除。

<!DOCTYPE html>
<html>
<head>
   <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
   <title>TutorialsPoint | jQuery</title>
   <style>
      .loader {
         border: 12px solid #f3f3f3; /* Light grey */
         border-top: 12px solid #3498db; /* Blue */
         border-radius: 50%;
         width: 60px;
         height: 60px;
         animation: spin 1s linear infinite;
      }
      @keyframes spin {
         0% {
            transform: rotate(0deg);
         }
         100% {
            transform: rotate(360deg);
         }
      }
   </style>
</head>
<body>
   <center>
      <h1>jQuery ajaxStop() Method</h1>
      <strong>Register a handler to be called when all Ajax requests have been completed.</strong>
      <br />
      <br />
      <button id="loadBtn">Load page</button>
      <div class="loader"></div>
      <div id="loaded"></div>
   </center>
   <script>
      $('.loader').hide()
      $(document).ajaxStop(function () {
         console.log('Triggered ajaxStop handler.')
         $('#loaded').text('The AJAX request have been completed.')
         $('.loader').hide()
      })
      $('#loadBtn').click(function () {
         $('.loader').show()
         $(document).load('https://tutorialspoint.tw/javascript/index.htm')
      })
   </script>
</body>
</html>

更新於:2022年7月20日

354 次瀏覽

開啟你的職業生涯

完成課程獲得認證

開始學習
廣告