【问题标题】:php json to javascript json format is not coming right as required resultphp json 到 javascript json 格式不是正确的结果
【发布时间】:2017-11-04 14:24:18
【问题描述】:

我正在尝试实现以下 json 很抱歉,但我不知道哪个是问题。

需要使用控制台的 JSON 屏幕截图:https://imgur.com/a/3HyI9

var requiredJson = {
        chart: {
            container: "#OrganiseChart-simple"
        },      
        nodeStructure: {text:{name:"Root"},children:[{text:{name:"naresh"},children:[{text:{name:"rahul1"}},{text:{name:"rahul123"}},{text:{name:"kapil1"},children:[{text:{name:"priya12"},children:[{text:{name:"amit12"}}]}]}]},{text:{name:"roshan"}},{text:{name:"Seppl"}},{text:{name:"pankaj1910"}}]}
    };

我的尝试:

我的尝试给了我这个结果:https://imgur.com/a/x1hot

当我使用回显到 json_encode($tree) 时,我的 php json :

[{"text":{"name":"Root"},"children":[{"text":{"name":"naresh"},"children":[{"text":{"name":"rahul1"}},{"text":{"name":"rahul123"}},{"text":{"name":"kapil1"},"children":[{"text":{"name":"priya12"},"children":[{"text":{"name":"amit12"}}]}]}]},{"text":{"name":"roshan"}},{"text":{"name":"Seppl"}},{"text":{"name":"pankaj1910"}}]}] ;

//$tree is a php array

var mytry = '<?php echo json_encode($tree); ?>';
 var requiredJson  = {
        chart: {
            container: "#OrganiseChart-simple"
        },

        nodeStructure: mytry 
    };

JS FIDDLE:https://jsfiddle.net/ueo0k9ys/1/

【问题讨论】:

    标签: javascript php jquery arrays json


    【解决方案1】:

    删除 php 输出周围的引号。他们告诉 javascript 编译器这是一个字符串而不是数组

    var mytry = <?php echo json_encode($tree); ?>;
    var requiredJson  = {
        chart: {
            container: "#OrganiseChart-simple"
        },
    
        nodeStructure: mytry 
    };
    

    【讨论】:

    • 结果不是预期的:你试着给我这个imgur.com/a/D2vzV
    • 随着您的尝试,nodeStructure 以数组的形式出现,但它应该是一个对象
    • 所以在服务器端调整它以返回您期望的结果
    • 如果结构不符合预期,则不会
    • 好的。我转换了我的 PHP 代码,现在我在 javascript Object [Object] 中得到了这个。我如何访问第二个对象?
    猜你喜欢
    • 2015-09-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多