我想使用 jQuery 的 AJAX 函数将键和值对发送到 PHP 文件,但是该函数没有发送数据。
PHP 代码与 HTML 代码位于同一个“Tester.php”文件中,如下所示:
<?php
if (array_key_exists("REQUEST_METHOD", $_SERVER) && $_SERVER["REQUEST_METHOD"] == "POST") {
echo "<pre>";
print_r($_POST); // always empty, no clue why!
echo "</pre>";
exit();
}
?>
<html>
<head>
<meta charset="utf-8">
<script type="text/javascript" src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
<script type="text/javascript" src="https://code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
<script>
$(document).ready(function() {
$.ajax({
type: "POST",
url: "Tester.php", // the same file/page
data: {
requestData: true,
message: "please print me!"
},
success: function(data) {
document.write("success!");
document.write(data);
},
error: function(xmlHttp) {
document.write("error!");
document.write(xmlHttp.responseText);
}
});
});
</script>
</head>
<body>
<p>Testing...</p>
</body>
</html>
这打印:
success!
Array
(
)
但是打印的数组应该包含传递给 $_POST 数组的数据中的“requestData: true”,但该数组却是空的。我做错了什么?谢谢!
最佳答案
HTML 文件 (36516400.html)
<html>
<head>
<title>36516400</title>
<script type="text/javascript" src="../../../assets/js/script.js"></script>
</head>
<body>
<h1>Welcome</h1>
<script type="text/javascript">
$(document).ready(function(){
$.ajax({
type:'POST',
data:{
'requestData':true,
'message':"please print me!"
},
url:'responce.php',
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
success:function(data){
alert(data);
}
});
})
</script>
</body>
</html>
PHP 文件 (responce.php)
<?php
echo "<pre>";
print_r($_REQUEST);
echo "<pre>";
?>
Chrome 控制台中的请求
关于javascript - jQuery 的 AJAX 不发布数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36516400/