为什么jQuery.post结束了在PHP的$ _ POST,和我的香草JS后不? [英] Why does jQuery.post end up in PHP's $_POST, and my vanilla JS post does not?
问题描述
我用香草JavaScript来发送使用JSON数据的AJAX POST请求:
I'm using vanilla JavaScript to send a AJAX post request with JSON data:
xhr.open(method, url,true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send(JSON.stringify(data));
的头看起来不错,但是在PHP $ _ POST
是空的。有几个相关问题上的SO关于这一点,如这个,但他们都建议使用:
The headers look good, but in PHP $_POST
is empty. There are several related questions on SO about this, like this one, but they all suggest using:
json_decode(file_get_contents("php://input"))
不过,如果我使用 jQuery.post
我的变量结束了在 $ _ POST
,所以它必须有可能。我的问题是如何?的什么可能我是做错了什么?或者,我能怎么改?
However, if I use jQuery.post
my variables end up in $_POST
, so it must be possible. My question is how? What might I be doing wrong? Or what could I change?
推荐答案
这是因为jQuery的你传递给一个字符串形式的格式数据转换,用应用程序/ x-WWW -form-urlen codeD
头,这是PHP识别并正确地创建 $ _ POST
超全局的。
That happens because jQuery converts the data you pass in to a string in the format of a form, with a application/x-www-form-urlencoded
header, which is something PHP recognizes and correctly creates the $_POST
superglobal from.
您本地XMLHtt prequest发送数据为字符串JSON格式与应用程序/ JSON
头,其中PHP不承认表单数据,并执行不能创建从 $ _ POST
阵列。
Your native XMLHttpRequest sends the data as a string in JSON format with the application/json
header, which PHP does not recognize as form data, and does not create a $_POST
array from.
在现代浏览器中,您可以使用 FORMDATA
创建可以通过PHP发送与Ajax和公认有效的表单数据
In modern browsers you can use formData
to create valid form data that can be sent with ajax and recognized by PHP
这篇关于为什么jQuery.post结束了在PHP的$ _ POST,和我的香草JS后不?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!