Javascript + PHP $ _POST数组为空

时间:2010-04-20 07:19:09

标签: php javascript http-post

尝试通过xmlhttp.open("POST", "url", true)(javascript)向服务器发送POST请求时,我得到一个空的$_POST array

Firebug显示正在发送数据。以下是来自Firebug的数据字符串:a=1&q=151a45a150...。但是$_POST['q']没有返回任何内容。

有趣的是,file_get_contents('php://input')确实拥有我的数据(上面的字符串),但PHP不知何故无法识别它。试过$ _POST和$ _REQUEST,没有任何作用。

正在发送标题:

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

感谢您提出任何建议。

4 个答案:

答案 0 :(得分:4)

您似乎缺少正确的Content-Type标头。这对POST请求是必要的:

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

答案 1 :(得分:2)

发送

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

标题代替text/plain

答案 2 :(得分:0)

你必须这样写:

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

答案 3 :(得分:0)

花了好几个小时试图找到解决这个问题的方法。

我犯了一个愚蠢的错误,就是连接几个我想成为参数的字符串,然后在整个地方调用encodeURIComponent。这当然意味着

foo=bar&this=that

成了

foo%3Dbar%26this%3Dthat

这当然是对PHP脚本的胡言乱语。虽然我怀疑会有很多人会像这样做一些愚蠢的事情,但我希望它可以帮助别人解决我刚刚给自己带来的麻烦....