使用JSON对象将PHP数组转换为JavaScript - 返回null

Gar*_*bit 1 javascript php jquery json

我在PHP中有一个数组,我将其传递给我在JavaScript中使用的视图.

所以我得到的是:

stdClass Object
(
    [tones] => Array
    (
        [0] => Array
        (
            [id] => 114
            [sleep_session_id] => 55
            [responded_to] => 
            [in_bed] => 1
            [created] => 1316443267104
            [inserted] => 2011-09-19 14:43:04
        )
    )
)

$(function () {
    var tones = $.parseJSON(<?php echo json_encode($this->tones); ?>);
    alert(tones);
});
Run Code Online (Sandbox Code Playgroud)

这导致了以下内容:

<script type="text/javascript">
    $(function () {
        var tones = $.parseJSON([{"id":114,"sleep_session_id":55}]);
        alert(tones);
    });
</script>
Run Code Online (Sandbox Code Playgroud)

所有我回来的都是null,jQuery肯定是加载的,我已经在jsonlint.com中检查了JSON,它看起来是有效的

希望你能帮助我

安迪

dur*_*uri 6

如果您的服务器端数据是JSON,则无需$.parseJSON在Javascript中使用.

$(function () {
    var tones = <?php echo json_encode($this->tones); ?>;
    alert(tones);
});
Run Code Online (Sandbox Code Playgroud)