如何使用GET方法在jQuery Ajax中发送数据?

jQuery.get(url,[data],[callback],[type])方法使用GET HTTP请求从服务器加载数据。

这是此方法使用的所有参数的描述-

  • url- 包含请求发送到的URL的字符串

  • 数据 -此可选参数表示将发送到服务器的键/值对。

  • callback- 此可选参数表示每当成功加载数据时将执行的函数。

  • type- 此可选参数表示要返回给回调函数的数据类型:“ 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://cdn.staticfile.org/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>