如何使用 jQuery 註冊一個在 Ajax 請求開始時呼叫的處理程式?


jQuery 是一個功能豐富的 JavaScript 庫。藉助 jQuery,我們可以執行很多操作,否則需要編寫大量程式碼才能實現。它使 DOM 操作、事件處理、動畫、ajax 等變得非常容易。

在本教程中,我們將學習如何註冊一個在第一個 Ajax 請求開始時呼叫的處理程式。Ajax 請求通常是瀏覽器為不同的任務(如 GET、POST 等)呼叫的 HTTP 請求。因此,當執行這些任務時,我們可以使用 jQuery 的 ajaxStart() 函式註冊一個處理程式。此函式在請求即將發出或請求開始時始終觸發。它在請求開始時註冊處理程式。

語法

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

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

示例 1

在以下示例中,我們使用 ajaxStart() 函式顯示 ajax 請求開始時的訊息。

<!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 ajaxStart() Method</h1>
      <strong>Register a handler to be called when the first Ajax request begins.</strong>
      <br />
      <br />
      <button id="loadBtn">Load page</button>
      <div id="tutorials"></div>
      <div id="loaded"></div>
   </center>
   <script>
      $(document).ajaxStart(function () {
         $('#loaded').text('The AJAX request have been started.')
      })
      $('#loadBtn').click(function () {
         $('#tutorials').load('https://tutorialspoint.tw/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: 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>
      <h1>jQuery ajaxStart() Method</h1>
      <strong>Register a handler to be called when the first Ajax requestBegins.</strong>
      <br />
      <br />
      <button id="loadBtn">Load page</button>
      <div class="loader"></div>
      <div id="loaded"></div>
   </center>
   <script>
      $('.loader').hide()
      $(document).ajaxStart(function () {
         $('#loaded').text('The AJAX request have started.')
         $('.loader').hide()
      })
      $('#loadBtn').click(function () {
         $('.loader').show()
         $(document).load('https://tutorialspoint.tw/javascript/index.htm')
      })
   </script>
</body>
</html>

更新於: 2022年7月20日

481 次檢視

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告