代码之家  ›  专栏  ›  技术社区  ›  chu8

关于使用AJAX和PHP获取$的基本问题

  •  -1
  • chu8  · 技术社区  · 7 年前

    以下是相关文件。

    file.php

    <?php 
    $bla = $_GET['pid'];
    echo $bla;
    ?>
    

    HTML

    示例站点的HTML代码 网址:

    (它包含一个按钮,当您单击该按钮时,它应该从URL中获取$u get值,即3)

    <!DOCTYPE html>
    <html>
    <head>
    <title>Some Page</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    
    </head>
    <body>
    
    <button class="fa fa-icon" onclick="someFunction()"></button>
    
    </body>
    </html>
    

    JS:

    <script>
    function someFunction(){
        $.ajax({
        method: 'POST', //I've tried 'GET' here too. doesnt make a difference
        url: "file.php", 
        success: function(result)
    {
    alert(result);}
    });
    }
    </script>
    

    <script>
    function someFunction(){
        $.ajax({
        method: 'POST', //I've tried 'GET' here too. doesnt make a difference
        url: "file.php", 
        data: {pid: 3}, // added this line
        success: function(result)
    {
    alert(result);}
    });
    }
    </script>
    

    当php文件的echo$bla为$_GET['pid']且url中的pid为=3时,该警报为空白,上面没有3。

    请注意,我并不是在试图解决某个特定的问题,也不是在试图理解为什么$\u GET在这个非常具体的情况下不起作用。

    1 回复  |  直到 7 年前
        1
  •  0
  •   Rory McCrossan Hsm Sharique Hasan    7 年前

    您没有在AJAX请求中发送任何数据,因此PHP无需读取和发送任何数据。要解决此问题,请包括 data 属性,该属性位于包含 pid

    function someFunction(){
      $.ajax({
        method: 'GET',
        url: "file.php", 
        data: {
          pid: 3
        },
        success: function(result) {
          console.log(result);
        }
      });
    }
    

    注意,我正在使用 method: 'GET' 在这里,这是很重要的,因为你正在使用 $_GET 在您的PHP中 POST console.log() 调试该值。 alert() 不应用于调试,因为它强制数据类型。