php - 我正在努力做,_POST 是空的

标签 php xmlhttprequest

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

我正在尝试通过 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 如何接收和解析它。

最佳答案

您应该将您的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.
)

关于php - 我正在努力做,_POST 是空的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31257444/

相关文章:

javascript xhr.upload 未定义。无法跟踪上传进度

javascript - 如何修复鼠标悬停时的下拉菜单不起作用

php - 如何在 Magento 中获取订单的完成日期

php - 在开关 php 中使用 strstr

PHP,读取通过 cURL 发送的 XML 文件

javascript - 我可以将以下代码发布到任何其他域吗?

javascript - 从 Ext.data.Store 访问 http 状态码

php - 带变量的 Html <A> 链接

javascript - 使用 XMLHttpRequest 的 AJAX 文件上传

javascript - XHR 请求的 CSRF 预防