jQuery 中 jQuery.load() 和 jQuery.get() 方法有什麼區別?


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/3.2.1/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>

jQuery get() 方法

jQuery.get( url, [data], [callback], [type] ) 方法使用 GET HTTP 請求從伺服器載入資料。

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

  • url − 包含傳送請求的 URL 的字串
  • data − 此可選引數表示將傳送到伺服器的鍵/值對。
  • callback − 此可選引數表示在資料成功載入時執行的函式。
  • type − 此可選引數表示返回給回撥函式的資料型別:“xml”、“html”、“script”、“json”、“jsonp”或“text”。

假設我們在 result.php 檔案中具有以下 PHP 內容,

<html>
   <?php
    if( $_REQUEST["name"] ) {

      $name = $_REQUEST['name'];
      echo "Welcome ". $name;
    }
   ?>
</html>

示例

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

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

更新於:2020-02-17

460 次瀏覽

開啟您的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.