为什么json_decode不起作用?

时间:2015-09-15 14:15:11

标签: php jquery

有人可以告诉我我在下面的代码中出错了吗?我想读一下json数组中1位的标题。

<script>
     $(document).ready(function(){
        $('#loading').click(function(){
            var NpPData = [
    {
        "title": "Professional JavaScript",
        "author": "Nicholas C. Zakas"
    },
    {
        "title": "JavaScript: The Definitive Guide",
        "author": "David Flanagan"
    },
    {
        "title": "High Performance JavaScript",
        "author": "Nicholas C. Zakas"
    }
];
            var NpPDataJSON = JSON.stringify(NpPData);
            alert(NpPDataJSON);
            $.post("prueba.php", NpPDataJSON, function(r){
                    $('#result').html('Answer from server: '+r);
                }, 
            'json').error(function(e){
                alert('FAiled: '+e.statusText);
            });
        });

      });
    </script>

和PHP:

$json = $_POST['NpPDataJSON'];
$data = json_decode($json);
echo $data[1]['title'];

1 个答案:

答案 0 :(得分:3)

将第二个参数设置为TRUE,让json_decode()返回array而不是stdClass个对象:

$json = $_POST['NpPDataJSON'];
$data = json_decode($json, true); // note the second argument 
echo $data[1]['title']; // returns 'JavaScript: The Definitive Guide'
  

当为TRUE时,返回的对象将被转换为关联数组。

另外,根据@Strynercomment,您似乎误用了$.post()函数。您需要为传递给服务器的数据设置名称,因此传递对象而不是变量:

$.post("prueba.php", {NpPDataJSON: NpPDataJSON}, function(r){/* ... */}, 'json');
相关问题