2017-10-18 132 views
-1

我想将数据从一个页面传递到另一个页面。我尝试了下面的代码。 result_display.php总是给我一个空的_POST数组。如果有人能指出我哪里错了,我将不胜感激。谢谢。在PHP中使用AJAX发布数据

的index.php

<?php 
ini_set('display_errors', 'On'); 
error_reporting(E_ALL); 
?> 

<!DOCTYPE html> 
<html lang="en"> 
<head> 
    <title>js save session</title> 
    <meta charset="utf-8"> 
    <meta name="viewport" content="width=device-width, initial-scale=1"> 
</head> 
<body> 
<input type="submit" id="mybutton" value="My Button"> 


<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> 

<script> 
    $(document).ready(function() { 

     $("#mybutton").click(function() { 

      $.ajax({ 
       method: "POST", 
       url: "./result_display.php", 
       data: {name: "John", location: "Boston"} 
      }) 
       .done(function (msg) { 
        console.log("Data Saved: " + msg); 
       }); 

      window.location.href = "result_display.php"; 
     }); 
    }); 
</script> 
</body> 
</html> 

result_display.php

<?php 
ini_set('display_errors', 'On'); 
error_reporting(E_ALL); 
?> 

<?php 
    var_dump($_POST); 
?> 
+0

尝试在这里的答案之一加入了“传统”的参数,以你的Ajax调用,如:https://stackoverflow.com/questions/5046930/jquery-send-string-as-post-parameters – agileMike

+0

谢谢回复。它也一样。我首先运行index.php。然后刷新result_display.php,仍然有一个空的_POST数组。 –

+0

啊,我误解了。其他意见是正确的。如果你做了一个POST然后一个GET,那么这两个请求是分开的。 GET不会有数据。如果在GET中需要这些参数,那么将它们作为查询字符串参数发送:window.location.href =“result_display.php?name = John&location = Boston”;然后你可能根本不需要POST。 – agileMike

回答

0

您需要删除您发送的AJAX调用后做重定向。

删除:window.location.href = "result_display.php";

+0

感谢您的回复。我删除了你提到的行,并添加了像agileMike建议的传统属性。它也一样。我首先运行index.php。然后刷新result_display.php,仍然有一个空的_POST数组。 –

0

我把重定向回来测试。在AJAX调用之后,我运行index.php并立即重定向到result_display.php。我发现POST后为什么会有GET。有人知道为什么请参阅附件截图。 enter image description here

+0

是因为重定向声明?但是,如果我删除重定向语句,我如何检查result_display.php中的_POST数组? –

+0

当您在浏览器中加载该页面时,您无法......正在执行GET请求。 _POST将为空白。如果你想*保存你的ajax请求的结果供以后查看,那么你必须将它们保存到一个数据库,并通过附加一个查询参数像'?id = 5'来加载它们,以便display_results知道要加载哪条记录。 。 – mpen

+0

好的。我懂了。非常感谢,mpen。 –