Ajax post到php在同一页不工作

Ajax post to php on same page not working

本文关键字:一页 工作 post php Ajax      更新时间:2023-09-26

我试图通过一个变量从jQuery到PHP。

经过研究,我发现最常见的建议是使用Ajax的Post和使用PHP存储post var。

我的PHP技能很好,但我不能说我的JavaScript技能相同。

这就是我正在做的,但似乎根本不起作用:

  // jquery libray included etc etc
  <script>
   $.ajax({
      type: "POST",
      url: "http://currentpage.com",
      data: "var=value",
      dataType: string
    });
 </script>
 </head>

<body>
<?php
if($_REQUEST["var"] == "value") {
    echo "var passed and stored";
}
?>
<script>
   $.ajax({
      type: "POST",
      url: "index.php",
      data: {var:'value'},
      dataType: 'text',
      success:function(data){
       // Test what is returned from the server
         alert(data);
      }
    });
 </script>

Try

<script>
   $.ajax({
      type: "POST",
      url: "http://currentpage.com",
      data: {variablename:'value'},
      dataType: "text", //Available types xml, json, script, html, jsonp, text
      success:function(response){
       //Returned from server
       alert(response);
      }
    });
 </script>