PHP 没有收到 jQuery AJAX 发送的我的 JSON

Ram*_*mon 3 php ajax jquery post json

我有一个困扰我的问题。我有一个发送 json 对象的 ajax 函数,我看到在 F12 Chrome 标头中解析了 JSON,我收到了成功警报。

$(document).ready(function() {
        var test = {'bob':'foo','paul':'dog'};
        $.ajax({
            url: "test.php",
            type: 'POST',
            contentType: "application/json; charset=utf-8",
            data: JSON.stringify(test),
            success: function(data) {
                alert("Bien: " + data);
            },
            failure: function(errMsg) {
                alert("Mal: " + errMsg);
            }
        });
});
Run Code Online (Sandbox Code Playgroud)

但是在我的 PHP 页面中,我看不到任何 POST,任何东西。我可以看到我的帖子已收到,但还有其他内容:

<?php

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
   echo "post"; //Result 'post'
}

foreach( $_POST as $stuff ) {
    echo $stuff; //Nothing at all
}

print_r(json_decode($_POST["data"], true)); // Undefined index: data
Run Code Online (Sandbox Code Playgroud)

在我使用的相同代码中

$.post( "test.php", { data: { name: "John", time: "2pm" } } );
Run Code Online (Sandbox Code Playgroud)

并且有效,然后是与代码相关的东西,但我真的看不出它是什么。

感谢您的帮助!

Ami*_*oni 5

试试这个

$results = json_decode(file_get_contents('php://input'));
echo $results->bob //Result foo
Run Code Online (Sandbox Code Playgroud)