英文:
Can I print data sent by AJAX via a post request directly in a php page
问题
<script>
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) {
window.location.href = "2.php";
}
};
xhr.send("username=John&email=john@example.com");
</script>
<?php
$username = $_POST['username'];
$email = $_POST['email'];
echo "Received username: " . $username . "<br>";
echo "Received email: " . $email;
事实上,我已经尽力了,但仍然不能直接在php中打印数据,可能是我的基础不够扎实,希望一些高手能教我,写写代码。
英文:
I wanted to send a post request to a php page via ajax and then print it in the php page with $_POST, but I found that I couldn't jump to the page and then print out the data like I could with a form
<script>
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) {
window.location.href = "2.php"
}
};
xhr.send("username=John&email=john@example.com");
</script>
<?php
$username = $_POST['username'];
$email = $_POST['email'];
echo "Received username: " . $username . "<br>";
echo "Received email: " . $email;
In fact, I have done everything I can think of, but still can not achieve direct print data in php, should be my foundation is too poor, I hope that some master can teach me, write write
答案1
得分: 1
<form id="my-account-form" method="POST" action="2.php">
<input type="hidden" name="username" value="">
<input type="hidden" name="email" value="">
</form>
...
...
...
<script>
// 使用此函数填写用户名和密码然后提交。
function submitAccount(username, password) {
const form = document.getElementById('my-account-form');
form.querySelector('input[name=username]').value = username;
form.querySelector('input[name=password]').value = password;
form.submit();
}
submitAccount('John', 'john@example.com');
</script>
英文:
If you simply want the user to be redirected to the submission PHP, the simplest way is to simply submit a POST form:
<form id="my-account-form" method="POST" action="2.php">
<input type="hidden" name="username" value="">
<input type="hidden" name="email" value="">
</form>
...
...
...
<script>
// Use this function to fill in username + password and submit.
function submitAccount(username, password) {
const form = document.getElementById('my-account-form');
form.querySelector('input[name=username]').value = username;
form.querySelector('input[name=password]').value = password;
form.submit();
}
submitAccount('John', 'john@example.com');
</script>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论