2012-01-27 153 views
1

我在PHP中使用了一个数组,我传递给了我在JavaScript中使用的视图。使用JSON对象将PHP数组转换为JavaScript - 返回null

因此,我所得到的是:

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); 
}); 

导致沿着线的东西:

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

所有我得到回来为空,jQuery是肯定加载和我检查了JSON在jsonlint.com,它似乎有效

希望你能帮助我走出

安迪

回答

6

如果你的服务器端数据是JSON,有没有必要在Javascript中使用$.parseJSON

$(function() { 
    var tones = <?php echo json_encode($this->tones); ?>; 
    alert(tones); 
}); 
+0

谢谢:)愚蠢的错误! – Garbit 2012-01-27 11:32:29

2

parseJSON解析JSON字符串,所以附上您的编码阵列中的引号:

$(function() { 
    var tones = $.parseJSON('<?php echo json_encode($this->tones); ?>'); 
    alert(tones); 
}); 

See this example

+0

感谢您的帮助:) – Garbit 2012-01-27 11:32:52

4
$(function() { 
     var tones = $.parseJSON('[{"id":114,"sleep_session_id":55}]'); 
     alert(tones); 
    }); 
+0

耶稣,我一定还睡着了:D谢谢你们。这么愚蠢的时候,这样的诀窍可以让你在StackOverflow上发布足够的内容,以便意识到你已经提出了一个非常愚蠢的问题:)再次感谢所有人。我最终只是回应了php json_encode就可以了。看起来整洁,我不信任js:D – Garbit 2012-01-27 11:31:33

+0

它发生在星期五! hehehe – 2012-01-27 11:47:26