2014-02-14 37 views
0

我很猶豫要問,但到目前爲止我還沒有找到任何解決方案。我一直認爲,這可能只是一個愚蠢的錯誤,但我找不到它。jQuery ajax post:PHP get的沒有內容

我有一個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瀏覽器告訴我,在控制檯中,該請求的數據是正確的,並已發送。當試圖訪問foo內PHP,一切都是空的:

var_dump($_POST); // array(0) 
$foo = file_get_contents("php://input"); 
var_dump($foo); // string(0) 

當我試着使用捲曲文章中,我得到的結果在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配置有問題,但我已將always_populate_raw_post_data = On設置在我的php.ini中。

我也試過沒有contentTypedataType,效果一樣。

+1

不是同樣的問題? http://stackoverflow.com/questions/298745/how-do-i-send-a-cross-domain-post-request-via-javascript – Nostalgie

+0

不幸的是沒有。我可以到達服務器,並且每次都返回輸出,但來自PHP的請求變量是空的。 – 23tux

+0

嗯爲什麼stringify?你可以發佈數據:{foo:「bar」},不知道它是否會有所作爲。 – Esko

回答

1

您要發送的字符串,而不是JSON,解決這個問題是這樣的:

$.ajax({ 
    url: "res.php", 
    type: "POST", 
    data: { foo: "bar" }, 
    success: function(result) { 
     console.log(result); 
    } 
}); 

print_r($_POST)返回此:

Array 
(
    [foo] => bar 
) 
+0

感謝您的回答。我在沒有'dataType'的情況下嘗試了它,並且使用和不使用stringify。不幸的是,在查看'file_get_contents(「php:// input」)'時,我仍然沒有得到PHP的結果。任何其他想法? – 23tux

+0

編輯我的答案,測試和工作完美。一探究竟 –