【发布时间】:2020-12-29 16:04:49
【问题描述】:
我有两个 PHP 页面。在其中一个页面上,我想在按下按钮时将数据发布到另一个页面。但是,当我尝试从其他页面访问 post 数组时,它显示为空。如果有人能告诉我哪里出错了,我将不胜感激。 (另外我不能用html表单发帖)
页面调用 test2.php:
<?php
if(isset($_POST['testing1'])){
die(json_encode($_POST));
}
?>
<html>
<head>
<link rel="stylesheet" type="text/css" href="styles.css">
<link rel="stylsheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js" integrity="sha512-s+xg36jbIujB2S2VKfpGmlC3T5V2TF3lY48DX7u2r9XzGzgPsa6wTpOQA7J9iffvdeBN0q9tKzRxVxw1JviZPg==" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/gh/emn178/chartjs-plugin-labels/src/chartjs-plugin-labels.js"></script>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
</head>
<body>
<button id="testbtn" onclick="location.href='test1.php'">Test Button</button>
<script>
$(document).ready(function(){
$('#testbtn').click(function() {
$.ajax({
method: 'POST',
url: 'test1.php',
data: {
testing1: 'string1',
testing2: '111'
},
success: function(data){
alert(data);
output = JSON.parse(data);
}
});
});
});
</script>
</body>
</html>
名为 test1.php 的页面:
<?php
$testvar = json_encode($_POST);
echo $testvar;
?>
<html>
<head>
<link rel="stylesheet" type="text/css" href="styles.css">
<link rel="stylsheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js" integrity="sha512-s+xg36jbIujB2S2VKfpGmlC3T5V2TF3lY48DX7u2r9XzGzgPsa6wTpOQA7J9iffvdeBN0q9tKzRxVxw1JviZPg==" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/gh/emn178/chartjs-plugin-labels/src/chartjs-plugin-labels.js"></script>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
</head>
<body>
</body>
</html>
【问题讨论】:
-
试试
json_encode($_REQUEST); -
您正在尝试将响应解析为 json,即使您似乎也在返回 HTML。这将使
JSON.parse()失败(并在控制台中抛出错误)。 -
@Sintuz - 该链接在这里并不真正相关,因为 OP 只是试图将一些数据发布到另一个页面,而该链接是将其传递到多个页面。
-
可能想删除
onclick="location.href='test1.php'",因为onclick=在$("#testbtn").click之前触发 - 所以它甚至没有尝试 ajax(你可以通过使用浏览器的调试来确认这一点)。您只是在没有 POST 的情况下打开第二页,因此没有 POST 数据。