开发者

Javascript + PHP $_POST array empty

开发者 https://www.devze.com 2022-12-28 00:17 出处:网络
While trying to send a POST request via xmlhttp.open(\"POST\", \"url\", true) (javascript) to the server I get an empty $_POST array.

While trying to send a POST request via xmlhttp.open("POST", "url", true) (javascript) to the server I get an empty $_POST array.

Firebug shows that the data is being sent. Here is the data string from Firebug: a=1&q=151a45a150.... But $_POST['q'] returns nothing.

The interesting thing is that file_get_contents('php://input') does have my data (the string above), but PHP somehow doesn't recognize it. Tried both $_POST and $_REQUEST, nothing works.

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: k开发者_运维知识库eep-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. This is necessary for POST requests:

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


Send a

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

header instead of 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. This of course meant that

foo=bar&this=that

became

foo%3Dbar%26this%3Dthat

which of course is gibberish to a PHP script. 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....

0

精彩评论

暂无评论...
验证码 换一张
取 消