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


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>

更新於:2020 年 2 月 17 日

3 千次觀看量

啟動你的 事業

完成課程以獲得認證

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