簡體   English   中英

Javascript + PHP $ _POST數組為空

[英]Javascript + PHP $_POST array empty

嘗試通過xmlhttp.open("POST", "url", true) (javascript)向服務器發送POST請求時xmlhttp.open("POST", "url", true)我得到一個空的$_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

感謝您的任何建議。

看來您缺少正確的Content-Type標頭。 這對於POST請求是必需的:

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

寄一個

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

標頭,而不是text/plain

您必須這樣寫:

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

只是花了幾個小時試圖找到解決這個問題的方法。

我犯了一個愚蠢的錯誤:將多個我想作為參數的字符串連接起來,然后在整個代碼中調用encodeURIComponent 這當然意味着

foo=bar&this=that

成為

foo%3Dbar%26this%3Dthat

當然,這對於PHP腳本來說毫無用處。 雖然我懷疑可能會有很多人會做這樣的愚蠢的事情,但我希望它可以減輕我剛剛給自己帶來的頭痛。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM