[英]jQuery ajax post: PHP get's no content
我很想問,但是到目前為止我還沒有找到任何解決方案。 我一直以為,這可能只是一個愚蠢的錯誤,但我找不到。
我有一個jQuery 2.1 ajax POST到我的PHP服務器:
$.ajax({
url: "http://my-server.com/post-example.php",
type: 'POST',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
data: JSON.stringify({ foo: "bar" }),
success: function(data) {
console.log("SUCCESS");
},
});
Safari在控制台中告訴我,請求數據正確且已發送。 嘗試在PHP中訪問foo
,所有內容均為空:
var_dump($_POST); // array(0)
$foo = file_get_contents("php://input");
var_dump($foo); // string(0)
當我嘗試使用curl進行POST時,我在php://input
得到結果:
curl -v -X POST -H "Content-Type: application/json" -d '{"foot":"bar"}' http://www.my-server.de/post-example.php
// on PHP side
var_dump($_POST); // array(0)
$foo = file_get_contents("php://input");
var_dump($foo); // string(13) "{"foo":"bar"}"
我找不到原因。 也許我的PHP配置有問題,但是我已經在php.ini
設置了always_populate_raw_post_data = On
。
我也試過沒有contentType
和dataType
,效果相同。
您正在發送字符串而不是JSON,請像這樣修復它:
$.ajax({
url: "res.php",
type: "POST",
data: { foo: "bar" },
success: function(result) {
console.log(result);
}
});
print_r($_POST)
返回以下內容:
Array
(
[foo] => bar
)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.