使用 jquery 发布 JSON 数据给了我空变量


Posting JSON data using jquery gives me empty variable

我有这个html/javascript:

<html>
    <head>
    </head>
    <body>
        <script src="view/backoffice/assets/plugins/jquery/jquery-1.11.1.min.js" type="text/javascript"></script>
        <script>
            $(document).ready(function(){
                var data = {'user_id':'2680',
                            'ship_to_name':'John Doe',
                            'ship_to_address':'Somewhere in Jawa Timur',
                            'ship_to_city':'Surabaya',
                            'ship_to_area':'Wonocolo',
                            'ship_to_phone':'080000000'};
                $.ajax({
                    url: "../controller/ctrl.php",
                    type: 'POST',
                    contentType:'application/json',
                    data: JSON.stringify(data),
                    dataType:'json'
                });
            });
        </script>
    </body>
</html>

我的服务器上有这个 PHP:

<?php
    $jsonReceiveData = json_encode($_POST);
    file_put_contents('storedvar.php', $jsonReceiveData);
?>

但我storedvar.php得到的只是 JSON 的空变量。 就像这个[].

为什么我无法获取 JSON 发送的数据?谢谢。

您的数据是 json ,而不是字符串。

像这样替换它,但不要拆分行。

 var data = "{'user_id':'2680',"+
                            "'ship_to_name':'John Doe',"+
                            "'ship_to_address':'Somewhere in Jawa Timur',"+
                            "'ship_to_city':'Surabaya',"+
                            "'ship_to_area':'Wonocolo',"+
                            "'ship_to_phone':'080000000'}";

如果这有效,您可能希望删除字符串并查看原始 JSON 是否有效。