我在PHP中使用echo $_POST
尝试$.ajax
但没有成功。在Xdebug中,我看到$_POST
得到正确的值并执行echo $_POST
行,但我一直得到else
输出子句。同样在chrome中我看到发送的标头有效。所有代码都在同一页面index.php。
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery.post demo</title>
<script src="https://code.jquery.com/jquery-2.2.0.min.js"></script>
</head>
<body>
<button type="button" id="but">Click Me!</button>
<script>
$('#but').click(function() {
$.ajax({
type: "POST",
url: "index.php",
data: {name: "John"},
success: function() {
alert('success');
}
});
});
</script>
</body>
</html>
<?php
if ($_SERVER['REQUEST_METHOD'] == "POST") {
echo $_POST['name'];
} else {
echo "Nothing to Show";
}
?>
答案 0 :(得分:1)
目前正在返回整个页面以响应您的AJAX请求; HTML和所有。您还没有在JS代码中检索从请求返回的值,为此您只需要在success
处理程序上接受参数。试试这个:
在其自己的文件中,请说foo.php
:
<?php
if ($_SERVER['REQUEST_METHOD'] == "POST") {
echo $_POST['name'];
} else {
echo "Nothing to Show";
}
?>
然后在你的HTML中:
<script>
$('#but').click(function() {
$.ajax({
type: "POST",
dataType: 'text', // to ensure jQuery doesn't try to deserialise the repsonse
url: "foo.php",
data: { name: "John" },
success: function(response) {
console.log(response.trim()); // = 'John'
}
});
});
</script>
答案 1 :(得分:0)
Ajax将返回响应,您可以使用该响应进行显示。它不会在同一页面上工作。
尝试如下:
main.php
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery.post demo</title>
<script src="https://code.jquery.com/jquery-2.2.0.min.js"></script>
</head>
<body>
<button type="button" id="but">Click Me!</button>
<div id="result"></div>
<script>
$('#but').click(function() {
$.ajax({
type: "POST",
url: "test.php",
data: {name: "John"},
success: function(data) {
alert('success');
$('#result').html(data);
}
});
});
</script>
</body>
</html>
test.php的
<?php
if ($_SERVER['REQUEST_METHOD'] == "POST") {
echo $_POST['name'];
} else {
echo "Nothing to Show";
}
?>