JSON.parse使用php's的json_encode方法

JSON.parse produces a syntax error with php's json_encode method

本文关键字:json encode 方法 使用 parse php JSON      更新时间:2023-09-26

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

在我的js中,我使用

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

当我加载页面时,我会得到chrome中的UncaughtSyntax Error: Unexpected token o,而在firefox中我会得到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"});

我看不出有什么问题,可以帮我一下。

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

或者你甚至什么都不需要做。它已经是一个对象。

就像。。。

var dbTree = <?php echo $tree; ?>;
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);

只需去掉解析函数。