Home >Backend Development >PHP Tutorial >Tips for PHP page jump to pass POST data
Title: Tips for PHP page jump to pass POST data
With the continuous development of web development, we often need to pass data between pages, one of which A common way is to pass data through the POST method. In PHP, how to transfer POST data when page jumps? This article explains some techniques and provides specific code examples.
The most common way to pass POST data is through form submission. For example, we have a form that contains data, and by clicking the submit button we jump to another page and pass the data.
<form method="post" action="target.php"> <input type="hidden" name="data" value="hello"> <button type="submit">Submit</button> </form>
In the target page target.php
, the passed data can be obtained through the $_POST
super global variable:
<?php if(isset($_POST['data'])){ $data = $_POST['data']; echo "传递的数据是:".$data; } ?>
In addition to form submission, we can also use JavaScript to pass POST data when page jumps. This function can be achieved by sending a POST request through the XMLHttpRequest
object.
<script type="text/javascript"> var xhr = new XMLHttpRequest(); xhr.open("POST", "target.php", true); xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); xhr.send("data=hello"); // 页面跳转 window.location = "target.php"; </script>
In target.php
, you can also obtain data through $_POST
:
<?php if(isset($_POST['data'])){ $data = $_POST['data']; echo "传递的数据是:".$data; } ?>
Another method is to pass POST data through Session. When sending a POST request, store the data in the Session and obtain the data through the Session in the target page.
<?php session_start(); $_SESSION['data'] = $_POST['data']; header("Location: target.php"); ?>
In target.php
, you can obtain the passed data through $_SESSION
:
<?php session_start(); if(isset($_SESSION['data'])){ $data = $_SESSION['data']; echo "传递的数据是:".$data; unset($_SESSION['data']); // 清除Session中的数据 } ?>
Through the above method, we can achieve on the page The function of passing POST data when jumping. Whether you use form submission, JavaScript or Session, in actual development, you can choose the appropriate method to transfer data according to the specific situation to improve user experience and development efficiency.
The above is the detailed content of Tips for PHP page jump to pass POST data. For more information, please follow other related articles on the PHP Chinese website!