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


jQuery.post( url, [data], [callback], [type] ) 方法會使用 POST HTTP 請求從伺服器載入頁面。

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

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

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

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

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

以下是關於如何在 jQuery Ajax 中使用 POST 方法傳送資料的實現程式碼片段。

   <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){
               
               $.post(
                  "result.php",
                  { name: "John" },
                  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:cc0;">
         STAGE
      </div>
       
      <input type = "button" id = "driver" value = "Load Data" />
       
   </body>

更新於: 2020-06-15

4K+ 檢視次數

開啟您的 職業

透過完成課程獲得認證

立即開始
廣告
© . All rights reserved.