不明白为什么我不用我的脚本更改我的 PHP 变量


don't understand why i'm not changing my php variable with my script

我正在尝试自学如何将AJAX与PHP一起使用。 但是,我无法让我的(可能损坏的)AJAX 代码来更改我的$things变量的值。 相反,发生的情况是重新加载索引.php页面并添加一个全新的按钮。 这是我的代码:

<?php
      $things = 0;
?>
    <!DOCTYPE html>
    <html>
    <head>
    <title>testing</title>
    <script>
    function changeMe()
    {
       var xmlhttp;
       if (window.XMLHttpRequest)
       {
          xmlhttp = new XMLHttpRequest();
       }
       xmlhttp.onreadystatechange=function()
       {
          if (xmlhttp.readyState==4 && xmlhttp.status==200)
          {
             document.getElementById("changetest").innerHTML=xmlhttp.responseText;
          }
       }
       var things = "<?php echo $things; ?>";
       things++;
       xmlhttp.open("GET","index.php?things="+things,true);
       xmlhttp.send();
    }
    </script>
    </head>
    <body>
    <?php
      echo "<p>Things = <span id='"changetest'"" . $things . "</span></p>";
    ?>
    <button type="button" onclick="changeMe()">Change Content</button>
    </body>
    </html>

关于我在哪里搞砸了的任何线索?

我可以看到至少两个问题:

  • 您没有使用要发送回服务器的变量$_GET['things']任何地方。相反,您始终将其设置为0因此您将永远不会看到其他任何内容;
  • 您正在发布到原始 php 文件。这意味着响应将是完整的 html 页面,包括head等。您可能想要一个单独的文件来仅发回您真正需要的内容。

一个单独的 php 文件的例子就是回显发送的内容:

<?php
echo 'I sent the number: ' . intval($_GET['things']);

现在你应该向这个文件发出ajax请求,而不是index.php

您应该

删除"<?php echo $things; ?>";周围的引号并使其var things = <?php echo "'".$things."'"; ?>