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


在本教程中,我們將學習如何註冊一個處理程式,以便在使用 jQuery 的 Ajax 請求完成後呼叫它。Ajax 請求通常是瀏覽器為各種任務(例如 **GET、POST** 等)呼叫的 **HTTP** 請求。因此,當任務執行完成後,我們可以使用 jQuery 的 **ajaxComplete()** 函式註冊一個處理程式。此函式在請求完成後始終被觸發。

語法

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

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

**說明** - 假設我們在 API 上有一個 GET 請求。當 API 返回結果時,jQuery 檢查是否有任何請求處於掛起狀態。如果沒有,則 jQuery 觸發 ajaxStop() 函式。

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

示例 1

在以下示例中,我們顯示了當 ajax 請求使用 ajaxComplete() 函式完成時顯示的訊息。

<!DOCTYPE html>
<html>
<head>
   <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
   <title>TutorialsPoint | jQuery</title>
</head>
<body>
   <center>
      <h2>jQuery ajaxComplete() Method</h2>
      <strong>Registers a handler to be called when Ajax requests complete.</strong>
      <br />
      <br />
      <button id="loadBtn">Load page</button>
      <div id="tutorials"></div>
      <div id="loaded"></div>
   </center>
   <script>
      $(document).ajaxComplete(function () {
         $('#loaded').text('The AJAX requests completed.')
      })
      $('#loadBtn').click(function () {
         $('#tutorials').load('./index.html')
      })
   </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: 16px solid #f3f3f3; /* Light grey */
         border-top: 16px solid #3498db; /* Blue */
         border-radius: 50%;
         width: 120px;
         height: 120px;
         animation: spin 2s linear infinite;
      }
      @keyframes spin {
         0% {
            transform: rotate(0deg);
         }
         100% {
            transform: rotate(360deg);
         }
      }
   </style>
</head>
<body>
   <center>
      <h2>jQuery ajaxComplete() Method</h2>
      <strong>Rregisters a handler to be called when Ajax requests complete.</strong>
      <br />
      <br />
      <button id="loadBtn">Load page</button>
      <div class="loader"></div>
      <div id="loaded"></div>
   </center>
   <script>
      $('.loader').hide()
      $(document).ajaxComplete(function () {
         $('#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-07-20

953 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

立即開始
廣告