简体   繁体   English

PHP未收到jQuery AJAX发送的JSON

[英]PHP does not receive my JSON sent by jQuery AJAX

I have a problem that puzzles me. 我有一个困扰我的问题。 I have an ajax function that sends a json object, and I see the JSON parsed in the F12 Chrome Headers, and I receive the success alert. 我有一个发送一个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);
            }
        });
});

But in my PHP page I cannot see any POST, anything. 但是在我的PHP页面中,我看不到任何POST,任何内容。 I can see that my post is received but anything else: 我可以看到收到了我的帖子,但除此之外:

<?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

In the same code I use 在相同的代码中,我使用

$.post( "test.php", { data: { name: "John", time: "2pm" } } );

and works, then is something related with the code, but I cannot really see waht is it. 并且可以正常工作,那么这与代码有关,但是我真的看不出来是什么。

Thank you for your help! 谢谢您的帮助!

try this instead 试试这个代替

$results = json_decode(file_get_contents('php://input'));
echo $results->bob //Result foo

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM