简体   繁体   English

Javascript + PHP $ _POST数组为空

[英]Javascript + PHP $_POST array empty

While trying to send a POST request via xmlhttp.open("POST", "url", true) (javascript) to the server I get an empty $_POST array . 尝试通过xmlhttp.open("POST", "url", true) (javascript)向服务器发送POST请求时xmlhttp.open("POST", "url", true)我得到一个空的$_POST array

Firebug shows that the data is being sent. Firebug显示正在发送数据。 Here is the data string from Firebug: a=1&q=151a45a150... . 这是Firebug的数据字符串: a=1&q=151a45a150... But $_POST['q'] returns nothing. 但是$_POST['q']返回任何内容。

The interesting thing is that file_get_contents('php://input') does have my data (the string above), but PHP somehow doesn't recognize it. 有趣的是, file_get_contents('php://input')确实拥有我的数据(上面的字符串),但是PHP却以某种方式无法识别它。 Tried both $_POST and $_REQUEST, nothing works. 尝试$ _POST和$ _REQUEST都无效。

Headers being sent: 标头发送:

POST /test.php HTTP/1.1
Host: website.com
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2.3) Gecko/20100401        Firefox/3.6.3
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-us;q=0.7,en;q=0.3
Accept-Encoding: gzip,deflate
Accept-Charset: utf-8;q=0.7,*;q=0.7
Keep-Alive: 115
Connection: keep-alive
Referer: http://website.com/
Content-Length: 156
Content-Type: text/plain; charset=UTF-8
Pragma: no-cache
Cache-Control: no-cache

Thank you for any suggestions. 感谢您的任何建议。

It looks like you're missing the correct Content-Type header. 看来您缺少正确的Content-Type标头。 This is necessary for POST requests: 这对于POST请求是必需的:

xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); 

Send a 寄一个

Content-Type: application/x-www-form-urlencoded

header instead of text/plain 标头,而不是text/plain

You have to write it like this: 您必须这样写:

xmlhttp.open("POST", "script.php", true);
xmlhttp.send("foo=bar&answer=42");

Just spent hours trying to find a fix for this very problem. 只是花了几个小时试图找到解决这个问题的方法。

I made the idiotic mistake of concatenating several strings which I wanted to be the parameters, and THEN calling encodeURIComponent on the whole lot. 我犯了一个愚蠢的错误:将多个我想作为参数的字符串连接起来,然后在整个代码中调用encodeURIComponent This of course meant that 这当然意味着

foo=bar&this=that

became 成为

foo%3Dbar%26this%3Dthat

which of course is gibberish to a PHP script. 当然,这对于PHP脚本来说毫无用处。 While I doubt there can be many people who would do something as silly as this, I hope it saves someone the headache I just gave myself.... 虽然我怀疑可能会有很多人会做这样的愚蠢的事情,但我希望它可以减轻我刚刚给自己带来的头痛。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM