JSON.parse使用php的json_encode方法产生语法错误

时间:2013-08-13 20:12:33

标签: php javascript

我有一个变量$data['tree'],它使用模型中的方法get_tree($id)从数据库中获取行数组。

在我的观点中,我使用

var dbTree = JSON.parse(<?php echo $tree; ?>);

当我加载页面时,我在chrome和firefox中获得UncaughtSyntax Error: Unexpected token o,我得到Syntax Error: Unexpected character

所以当我用chrome检查脚本元素时,js看起来像

var dbTree = JSON.parse({"id":"2","name":"sean","userId":"51fbd3f3a8f2ba1b5b000002","accountId":"51fbd3fca8f2ba1b5b000003","createdAt":"2013-08-02 16:09:34","numRuns":null,"contactExport":"","updatedAt":"2013-08-02 20:15:14","deployed":"1","template":"0","conversation_type":"Conversation"});

我没有看到任何错误,有些人可以帮助我。

2 个答案:

答案 0 :(得分:2)

JSON.parse应该与字符串一起使用,而不是对象。

或者你甚至不需要做任何事情。它已经是一个对象。

就像......

var dbTree = <?php echo $tree; ?>;

答案 1 :(得分:2)

var dbTree = {"id":"2","name":"sean","userId":"51fbd3f3a8f2ba1b5b000002","accountId":"51fbd3fca8f2ba1b5b000003","createdAt":"2013-08-02 16:09:34","numRuns":null,"contactExport":"","updatedAt":"2013-08-02 20:15:14","deployed":"1","template":"0","conversation_type":"Conversation"};
// Test it works
console.log(dbTree);

摆脱解析功能。