[英]Jquery $.post() data cannot be retrieved as PHP variable
我很难让 Ajax 请求 $.post() 从 Jquery 工作。 我想使用 $.post() 从表单发送数据并将其检索为 php 变量,以便进一步将它们处理到 SQL 数据库中。
下面,我将我的问题的简化版本放在一页代码中(当 function 被触发时,Jquery 发布到同一页面)。 我希望使用此方法以在提交表单时不触发页面重新加载。
问题:我的 post() function 有效,我收到正确的警报,说明发布的数据,但是,在我提交请求后,print_r($_POST) 检查方法保持为空。
我的问题:如何将发布的数据放入 php 变量($_POST['name'] & $_POST['email']?
<!DoCType html>
<html lang="fr-CH">
<head>
<title> TEST </title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="/JS/jquery-3.3.1.min.js"></script>
</head>
<body>
<?php
print_r($_POST); // always returns an empty array, even after clicking the submit button
if (isset($_POST['name'])) {
echo "PHP received data";
} else {
echo "It did not work";
}
?>
<div class='caseform'>
<form id="form" method="post">
Name:<br> <input type="text" name="name"> <br>
Email:<br> <input type="text" name="email"> <br>
<button id="button"> Submit </button>
</form>
</div>
<script>
$( document ).ready(function() {
$("#button").click(function( event ) {
event.preventDefault();
var postData = $('#form').serialize();
// the $.post goes to the same php file "test.php"
var jqxhr = $.post("test.php", postData ,function() {
}).done(function() {
// this works, I get an alert with postData from my form (name=&email=)
alert(postData);
}).fail(function() {
alert("Error submitting the form.");
})
});
});
</script>
</body>
</html>
问题是您没有任何东西可以阻止后处理代码为 GET 请求运行。 当您最初加载页面时,它是一个 GET 请求,并且它正在运行您的print_r($_POST)
当然是空的。
将该代码包装在这样的检查中,并将其移动到文件的顶部。
<?php
if($_SERVER['REQUEST_METHOD'] == 'POST'){
print_r($_POST); // always returns an empty array, even after clicking the submit button
if (isset($_POST['name'])) {
echo "PHP received data";
} else {
echo "It did not work";
}
exit();
}
?><!DoCType html>
...
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.