console.log显示了数据,但php echo没有


console.log shows the data but php echo does not

index.php

<body>
<script>
var h = $(window).height();
alert (h); // works fine - result is 580
$.ajax({
    type: "POST",
    url: 'pass.php',
    data: {h : h},
    success:(function(data){
        console.log(data);  // works fine - 580
    })
});
</script>
<?php
include ("pass.php");
echo $h;  // doesn't work. there is no echo of 580
echo "323"; // this works as a test
?>

pass.php

$h = $_POST['h'];
echo $h;

那么,为什么我不能得到580作为index.phpecho $h;的结果呢?

您正在发出两个HTTP请求。

第一个请求是针对index.php的GET请求。该脚本include是从$_POST读取的pass.php。但是,这一次$_POST没有被填充,因为它是一个GET请求。因此CCD_ 9没有得到一个值。

第二个请求是针对pass.php的POST请求(来自JavaScript(。这一次$_POST被填充。

Ajax不会追溯更改服务器先前向浏览器发送的请求内容。如果您想更改用户对Ajax的响应,那么您需要使用JavaScript(在成功函数中(更改DOM。

让我们考虑一下这个问题。首先,PHP发现了以下PHP代码:

<?php
include ("pass.php"); // Okay, is an include in here, let's include the file
echo $h;
echo "323";
?>

包括之后:

<?php
$h = $_POST['h']; // Produces E_NOTICE because no index 'h' found
echo $h; // null
echo $h; // null
echo "323"; // 323
?>

结果是CCD_ 12。PHP代码中没有给出POST数据,因此$_POST["h"]为null,并且没有给出任何echo。您的ajax调用发送POST数据,因此它将以PHP打印。

data: {h : h}

这不是580:580吗?尝试

data: {"h" : h}