如何使用 GET 方法在 jQuery Ajax 中傳送資料?


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

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

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

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

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

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

示例

以下是使用 jQuery 實現 GET 方法的程式碼段 −

   <head>
      <title>The jQuery Example</title>
      <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>

更新於: 17-2 月-2020

3K+ 瀏覽量

開始你的 事業

透過完成課程獲得認證

開始
廣告
© . All rights reserved.