jQuery 中 jQuery.load() 和 jQuery.ajax() 方法的區別是什麼?


jQuery ajax() 方法

jQuery.ajax( options ) 方法使用 HTTP 請求載入遠端頁面。$.ajax() 返回它建立的 XMLHttpRequest 物件。在大多數情況下,您不需要直接操作該物件,但如果您需要手動中止請求,則可以使用它。

以下是此方法使用所有引數的說明:

  • options - 一組配置 Ajax 請求的鍵值對。所有選項都是可選的。

假設我們在result.html 檔案中有以下 HTML 內容:

<h1>THIS IS RESULT...</h1>

示例

以下是一個顯示此方法用法的示例。在這裡,我們使用成功處理程式來填充返回的 HTML:

   <head>
      <script src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
       
      <script>
         $(document).ready(function() {
            $("#driver").click(function(event){
               $.ajax( {
                  url:'result.html',
                  success:function(data) {
                     $('#stage').html(data);
                  }
               });
            });
         });
      </script>
   </head>
   
   <body>
   
      <p>Click on the button to load result.html file:</p>
       
      <div id = "stage" style = "background-color:blue;">
         STAGE
      </div>
       
      <input type = "button" id = "driver" value = "Load Data" />
       
   </body>

jQuery load() 方法

load( url, data, callback ) 方法從伺服器載入資料,並將返回的 HTML 放入匹配的元素中。

以下是此方法使用所有引數的說明:

  • url - 包含傳送請求的 URL 的字串。
  • data - 此可選引數表示與請求一起傳送的資料對映。
  • callback - 此可選引數表示請求成功時執行的函式。

假設我們在result.html 檔案中有以下 HTML 內容:

<h1>THIS IS RESULT...</h1>

示例

以下是顯示此方法用法的程式碼片段。

   <head>
      <script src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
       
      <script>
         $(document).ready(function() {
            $("#driver").click(function(event){
               $('#stage').load('result.html');
            });
         });
      </script>
   </head>
   
   <body>
   
      <p>Click on the button to load result.html file:</p>
       
      <div id = "stage" style = "background-color:cc0;">
         STAGE
      </div>
       
      <input type = "button" id = "driver" value = "Load Data" />
       
   </body>

更新於:2020年2月17日

355 次瀏覽

啟動您的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.