我是JavaScript的新手,只有最少的PHP经验。我花了几个小时在网上搜索并查看与我的问题相似的其他帖子,对于我的生活,我无法弄清楚。
我尝试使用POST通过XMLHTTPRequest发送一些信息。通过php://输入访问它时数据显示正常,但$ _POST数组本身没有任何内容。为什么呢?
我尝试过使用json_decode,但没有用。
提前感谢您的帮助。
<script>
var sendstring = "name=The Muffin Man&address=123 Drury Lane, Fairy Town, CA 01234";
poststuff(sendstring, function(data, responseCode) {
if (responseCode == 200) {
alert("Entry added to database");
}
else
{
alert("Failed. Response code is: " + responseCode + ", data: " + data);
}
});
function poststuff(sendstring, callback) {
var request = window.ActiveXObject ?
new ActiveXObject('Microsoft.XMLHTTP') :
new XMLHttpRequest;
request.onreadystatechange = function() {
if (request.readyState == 4) {
request.onreadystatechange = doNothing;
callback(request, request.status);
}
};
request.open('POST', "posttofile.php", true);
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.send(sendstring);
}
function doNothing() {}
</script>
posttofile.php:
<?php
$myFile = "data.txt";
$fh = fopen($myFile, 'a');
$postdata = serialize($_POST);
$phpinputdata = file_get_contents('php://input');
fwrite($fh, "postdata: " . $post_body . "\nphpinputdata: " . $phpinputdata);
fclose($fh);
?>
data.txt输出:
postdata:
phpinputdata: name=The Muffin Man&address=123 Drury Lane, Fairy Town, CA 01234