[英]Why is my $_POST empty but file_get_contents('php://input') is not?
When I POST
data to my server using a regular old form submit I can pull that data from the $_POST
variable, but when POST
ing JSON data via AJAX I need to access it via file_get_contents('php://input')
. 当我POST
使用一个普通的旧形式的数据到我的服务器提交我可以拉从数据$_POST
变量,但在POST
通过AJAX荷兰国际集团JSON数据,我需要通过访问它file_get_contents('php://input')
Why is that? 这是为什么? In both cases I am using the POST
method, are there some explicit headers I should be setting on my AJAX call? 在这两种情况下,我都使用POST
方法,我应该在AJAX调用中设置一些显式头吗? I have only ever come up against this problem on the current development server and have never had to use file_get_contents('php://input')
before. 我只是在当前的开发服务器上遇到过这个问题,而且以前从未使用过file_get_contents('php://input')
。 Is there a server setting somewhere? 是否在某处设置了服务器? Can I change this behaviour with a .htaccess? 我可以使用.htaccess更改此行为吗?
Add this to the top of your .php file: 将其添加到您的.php文件的顶部:
$_POST = json_decode(file_get_contents("php://input"), true);
so that the contents will be property decoded and available. 因此内容将被属性解码并可用。 After that, you can access individual keys as usual. 之后,您可以照常访问各个键。
So as far as I have been able to find out, this has something to do with the way the data is received by the server - PHP can't natively parse JSON. 据我所知,这与服务器接收数据的方式有关-PHP无法本地解析JSON。 Sending plain old JSON objects from Javascript to PHP will result in PHP not knowing what to do with the datatype, and thus it won't be able to prepopulate the appropriate global variables. 将原始的旧JSON对象从Javascript发送到PHP将导致PHP不知道如何处理数据类型,因此它将无法预填充适当的全局变量。
In order to get around it I added a check to my ajax wrapper function that intercepts the JSON, encodes is as a FormData
object and shoots that off to the server instead. 为了解决该问题,我向我的ajax包装函数添加了一个检查以拦截JSON,将其编码为FormData
对象,然后将其发送到服务器。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.