显示console.log的数据,但PHP回声不回声、数据、console、log

2023-09-10 14:52:38 作者:无敌小战神

的index.php

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

pass.php

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

那么,为什么我不能让 580 回声$ h的结果;而在 的index.php

推荐答案

您正在两个的HTTP请求。​​

You are making two HTTP requests.

第一个请求是的GET请求的index.php 。该脚本包括取值 pass.php 读取从 $ _ POST 。然而,这一次, $ _不填充POST ,是因为它是一个GET请求。 $ H 因此没有得到一个值。

The first request is a GET request for index.php. That script includes pass.php which reads from $_POST. However, this time around, $_POST is not populated because it is a GET request. $h therefore does not get a value.

第二个请求是一个POST请求(通过JavaScript)的 pass.php 。这一次 $ _ POST 填充。

The second request is a POST request (from JavaScript) for pass.php. This time $_POST is populated.

阿贾克斯不追溯改变什么服务器previously发送到浏览器的早期请求。如果你想改变什么,用户看到的响应阿贾克斯,那么你需要改变使用JavaScript的DOM(你成功的函数中)。

Ajax does not retroactively change what the server previously sent to the browser for an earlier request. If you want to change what the user is seeing in response to Ajax, then you need to change the DOM using JavaScript (inside your success function).