PHP $_POST
PHP $_POST
$_POST 包含通过 HTTP POST 方法接收的变量数组。
通过 HTTP Post 方法发送变量的主要有两种方式:
- HTML 表单
- JavaScript HTTP 请求
HTML 表单中的 $_POST
如果 HTML 表单的 method 属性设置为 "POST",则该表单会通过 HTTP POST 方法提交信息。
为了演示这一点,我们首先创建一个简单的 HTML 表单:
HTML 表单
<html> <body> <form method="POST" action="demo_request.php"> Name: <input type="text" name="fname"> <input type="submit"> </form> </body> </html>
当用户点击提交按钮时,表单数据会被发送到 <form> 标签的 action 属性中指定的 PHP 文件。
在 action 文件中,我们可以使用 $_POST 变量来收集输入字段的值。
PHP 文件
$name = $_POST['fname']; echo $name;
在下例中,我们将 HTML 表单和 PHP 代码放在了同一个 PHP 文件中。
我们还添加了一些额外的安全行。
实例
<html>
<body>
<form method="POST" action="<?php echo $_SERVER['PHP_SELF'];?>">
Name: <input type="text" name="fname">
<input type="submit">
</form>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = htmlspecialchars($_POST['fname']);
if (empty($name)) {
echo "Name is empty";
} else {
echo $name;
}
}
?>
</body>
</html>
JavaScript HTTP 请求中的 $_POST
在 JavaScript 中发送 HTTP 请求时,您可以指定 HTTP 方法为 POST。
为了演示这一点,我们首先创建一个包含 HTTP 请求的 JavaScript 函数:
JavaScript 函数
function myfunction() {
const xhttp = new XMLHttpRequest();
xhttp.open("POST", "demo_phpfile.php");
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.onload = function() {
document.getElementById("demo").innerHTML = this.responseText;
}
xhttp.send("fname=Mary");
}
}
上面的代码会:
- 发起一个 HTTP 请求
- 设置 HTTP 方法为 POST
- 设置有效的请求头
- 创建一个在请求完成时执行的函数
- 发送 HTTP 请求,并将变量
fname设置为Mary
查看当请求完成时执行的函数:
xhttp.onload = function() {
document.getElementById("demo").innerHTML = this.responseText;
}
它会尝试将在操作中得到的响应写入具有 id="demo" 的 HTML 元素。
让我们创建一个带有此类元素的 HTML 页面,以及一个执行该函数的按钮。
如果我们还添加了 JavaScript,则页面看起来像这样:
实例
如何从 HTTP 请求中发布和接收数据:
<html>
<script>
function myfunction() {
const xhttp = new XMLHttpRequest();
xhttp.open("POST", "demo_ajax.php");
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.onload = function() {
document.getElementById("demo").innerHTML = this.responseText;
}
xhttp.send("fname=Mary");
}
}
</script>
<body>
<button onclick="myfunction()">Click me!</button>
<h1 id="demo"></h1>
</body>
</html>
在接收此 HTTP 请求的 PHP 文件(demo_ajax.php)中,我们只需使用 $_POST 变量来检索 fname 变量,并将其作为响应写出。
PHP 文件
$name = $_POST['fname']; echo $name;