我正在努力做,_POST 是空的

I'm doing it the hard way and _POST is empty

我看了又看,但没有什么能完全触及这个问题。

我正在尝试通过 Chrome 中的 JavaScript* 发送 XMLHttpRequest。这是我的页面:

<!DOCTYPE html>
<html>
 <head>
  <title>ROAM</title>
  <script>
    function post_something() {
      var xmlhttp = new XMLHttpRequest();
      xmlhttp.open('POST', "post_test.php", true);
      xmlhttp.setRequestHeader('Content-Type', 'text/plain');
      xmlhttp.send("This is my text.");
      xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
          console.log(xmlhttp.responseText);
        }
      }
    }
  </script>
 </head>
 <body>
  <table>
    <tr><td><input type="button" value="POST a thingy"
                   onclick="javascript:post_something()">
            </input>
    </td></tr>
  </table>
 </body>
</html>

这是我的 PHP:

<?php
  print_r($_POST);
/>

这显示在控制台中:

Array
(
)

如果某个地方能告诉我 XMLHttpRequest.send 实际上在幕后做了什么,它到底发送了什么,PHP 如何解析它,以及 PHP 期望什么,我可以解决我自己就是这个蠢货。

*请理解我不想使用表格或 jQuery。我想直接使用 XMLHttpRequest 对象,直到我确切了解它的工作原理以及 PHP 接收和解析它的方式。

$_POST 包含请求正文中通过 application/x-www-form-urlencoded 发送的参数。由于您没有键=值对,因此 _POST 中没有任何内容。
要么试试

xmlhttp.send("x=This+is+my+text.");

$post = file_get_contents('php://input');

http://php.net/manual/de/wrappers.php.php

你应该将你的 Content-Type 声明为 application/x-www-form-urlencoded 并以 key1=value1&key2=value2&key3=value3.

的形式制作一个数据字符串
function post_something() {
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.open('POST', "post_test.php", true);
    xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    var data = "text=This is my text.&text2=This is my second text.";
    xmlhttp.send(encodeURI(data));
    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            console.log(xmlhttp.responseText);
        }
    }
}

输出:

Array
(
    [text] => This is my text.
    [text2] => This is my second text.
)