douzhong8856 2016-06-22 12:56
浏览 40
已采纳

php作为js变量的结果

I searched many topics on this site about my problem. Many of them helped me but I still have a major problem I can not solve.

I get Data via php file from a Sql DB. This php File converts the data into a json-string. Now I want to have this json String inside an js-File to build a Hyperbolic Tree out of this Data.

The problem is about this:

I have a php:

<?php

$categories = Category::getTopCategories();
$categories = array_values($categories);

echo json_encode($categories)

class Category
{
/**
 * The information stored in the database for each category
 */
public $id;
public $parent;
public $name;

// The child categories
public $children;

public function __construct()
{
    // Get the child categories when we get this category
    $this->getChildCategories();
}

/**
 * Get the child categories
 * @return array
 */
public function getChildCategories()
{
    if ($this->children) {
        return $this->children;
    }
    return $this->children = self::getCategories("parent = {$this->id}");
}

////////////////////////////////////////////////////////////////////////////

/**
 * The top-level categories (i.e. no parent)
 * @return array
 */
public static function getTopCategories()
{
    return self::getCategories('parent = 0');
}

/**
 * Get categories from the database.
 * @param string $where Conditions for the returned rows to meet
 * @return array
 */
public static function getCategories($where = '')
{
    if ($where) $where = " WHERE $where";
    $conn=mysqli_connect('localhost', 'root', '','praktikum');
    $sql = "SELECT * FROM nugget$where";
    $result = mysqli_query($conn,$sql);

    $categories = array();
    while ($category = mysqli_fetch_object($result, 'Category'))
        $categories[] = $category;

    mysqli_free_result($result);
    return $categories;
}
}

?>

that has this output

[{
"id": "1"
, "parent": "0"
, "name": "WI2"
, "children": [{
    "id": "2"
    , "parent": "1"
    , "name": "E-Business"
    , "children": [{
        "id": "4"
        , "parent": "2"
        , "name": "Vorlesung"
        , "children": []
    }, {
        "id": "5"
        , "parent": "2"
        , "name": "Uebung"
        , "children": []
    }]
}, {
    "id": "3"
    , "parent": "1"
    , "name": "E-Procurement"
    , "children": [{
        "id": "6"
        , "parent": "3"
        , "name": "Vorlesung"
        , "children": []
    }, {
        "id": "7"
        , "parent": "3"
        , "name": "Uebung"
        , "children": []
    }]
}]

}]

and I want to have the Output instead of the text behind "json" in this javascript method that is in an seperate file (example.js):

function init(){ 
//init data
var json = { /*
Hier stehen die ganzen Kinder drinnen
Einzelne Children durch Datenbankeinträge ersetzen
*/

    **"id": "1"
    , "parent": "0"
    , "name": "WI2"
    , "children": [{
        "id": "2"
        , "parent": "1"
        , "name": "E-Business"
        , "children": [{
            "id": "4"
            , "parent": "2"
            , "name": "Vorlesung"
            , "children": []
        }, {
            "id": "5"
            , "parent": "2"
            , "name": "Uebung"
            , "children": []
        }]
    }, {
        "id": "3"
        , "parent": "1"
        , "name": "E-Procurement"
        , "children": [{
            "id": "6"
            , "parent": "3"
            , "name": "Vorlesung"
            , "children": []
        }, {
            "id": "7"
            , "parent": "3"
            , "name": "Uebung"
            , "children": []
        }]
    }]**


};

so how do I get the variable $categories in the javascript file so json has the same output inside as I get when proceding: 'echo json_encode($categories); without the [{ tag at beginning and at the end.'

Tried with $.get("Testerich.php"); and other funtcions but it didnt work.

Thanks for your help aladin

</div>
  • 写回答

2条回答 默认 最新

  • duanlang1531 2016-06-22 13:25
    关注

    Suppose that your PHP returning json encoded data like as this :-

    // PHP

    <?php
    function getCategory()
    {
          echo json_encode(getCat());
    }
    ....
    ?>
    

    //JavaScript Code

    var myCategory ;
    
    $.ajax({
    
        url : "your-domain.com/...../getCategory",
        method : "POST",
        success : function (response)
        {
              myCategory = JSON.parse(response);
    
              // Now you have category information in JSON format 
              // Your code here 
        }
    

    });

    You can use myCategory variable in JavaScript to access the JSON tree.

    Use

     console.log(myCategory); 
    

    in JavaScript to know the variable structure .

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 (标签-UDP|关键词-client)
  • ¥15 关于库卡officelite无法与虚拟机通讯的问题
  • ¥15 qgcomp混合物线性模型分析的代码出现错误:Model aliasing occurred
  • ¥100 已有python代码,要求做成可执行程序,程序设计内容不多
  • ¥15 目标检测项目无法读取视频
  • ¥15 GEO datasets中基因芯片数据仅仅提供了normalized signal如何进行差异分析
  • ¥100 求采集电商背景音乐的方法
  • ¥15 数学建模竞赛求指导帮助
  • ¥15 STM32控制MAX7219问题求解答
  • ¥20 在本地部署CHATRWKV时遇到了AttributeError: 'str' object has no attribute 'requires_grad'