AJAX发送POST请求后,如何在PHP页面直接打印接收的数据?
问题分析与解决方案
你的代码核心问题是:AJAX发送POST请求和后续的window.location.href跳转是两个完全独立的HTTP请求。AJAX请求确实把POST数据发给了2.php,但跳转时发起的是新的GET请求,这个请求里没有携带任何POST参数,所以2.php在跳转后无法获取到之前的POST数据。
下面提供两种符合你需求的解决方案:
方案1:直接跳转到2.php并显示POST数据(无需AJAX)
如果你的目标就是跳转到2.php页面展示提交的数据,完全不需要用AJAX,直接用HTML表单提交更简单:
<form action="2.php" method="POST"> <input type="hidden" name="username" value="John"> <input type="hidden" name="email" value="john@example.com"> <button type="submit">提交</button> </form>
如果需要用JS触发提交,可以动态创建表单并提交:
// 动态创建表单 const form = document.createElement('form'); form.action = '2.php'; form.method = 'POST'; // 添加参数 const usernameInput = document.createElement('input'); usernameInput.type = 'hidden'; usernameInput.name = 'username'; usernameInput.value = 'John'; form.appendChild(usernameInput); const emailInput = document.createElement('input'); emailInput.type = 'hidden'; emailInput.name = 'email'; emailInput.value = 'john@example.com'; form.appendChild(emailInput); // 提交表单 document.body.appendChild(form); form.submit();
方案2:在当前页面显示2.php返回的数据(不跳转)
如果不想跳转页面,而是在当前页面展示2.php的输出,修改你的AJAX代码,把返回的内容插入到页面中即可:
var xhr = new XMLHttpRequest(); xhr.open("POST", "2.php", true); xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); xhr.onreadystatechange = function() { if (xhr.readyState === 4 && xhr.status === 200) { // 把返回的HTML插入到页面某个元素中,比如id为result的div document.getElementById('result').innerHTML = xhr.responseText; } }; xhr.send("username=John&email=john@example.com");
然后在当前页面添加一个用于显示结果的元素:
<div id="result"></div>
你的PHP代码不需要修改,保持原样即可。
内容的提问来源于stack exchange,提问作者user22060853
相关产品推荐
相关产品推荐

