php作为变量的结果js

时间:2016-06-22 12:56:58

标签: javascript php html json

我在这个网站上搜索了很多关于我的问题的主题。他们中的许多人帮助了我,但我仍有一个我无法解决的重大问题。

我通过php文件从Sql DB获取数据。这个php文件将数据转换为json-string。现在我想在js-File中使用这个json String来构建这个数据中的双曲树。

问题在于:

我有一个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;
}
}

?>

具有此输出

[{
"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": []
    }]
}]

}]

我希望在这个单独的文件(example.js)中的javascript方法中输出而不是“json”后面的文本:

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": []
        }]
    }]**


};

那么如何在javascript文件中获取变量$ categories,这样json在处理时的内部输出与我得到的相同:'echo json_encode($ categories);没有[{标签在开头和结尾。'

尝试使用$ .get(“Testerich.php”);和其他功能,但它没有用。

感谢您的帮助 阿拉丁

2 个答案:

答案 0 :(得分:0)

您不能在.js文件中使用PHP变量,因此您必须按照您所说的尝试发出AJAX请求,但在您提供的示例中,您没有使用回调,请确保您是像这样发出请求(假设您使用的是代码中显示的jQuery):

$.get("Testerich.php", function(data) {
    console.log(JSON.parse(data)); // use JSON.parse() to convert the string returned by "Testerich.php" to JSON
});

答案 1 :(得分:0)

假设您的PHP返回json编码数据,如下所示: -

// PHP

$loggedUser = $_SESSION["user"];
$userfile   = file_get_contents('projekte_'.$loggedUser.'.json');
$jsonarray  = json_decode($userfile);
$index      = count($jsonarray);

for ($i = 0; $i < $index; $i++) {
    $style = "cssOdd";
    if ($i % 2 != 0) {
        $style = "cssEven";
    }

    if($loggedUser === $jsonarray[$i]->User) {
        echo
            '<tr class="' . $style . '">
            <td align="center">' . $jsonarray[$i]->User . ' </td>
            <td align="right">' . $jsonarray[$i]->Nr . ' </td>
            <td>' . $jsonarray[$i]->Kuerzel . ' </td>
            <td>' . $jsonarray[$i]->Projekttitel . ' </td>
            <td>' . $jsonarray[$i]->Kunde . '</td>
        </tr>';
    }
}

// JavaScript代码

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

});

您可以在JavaScript中使用myCategory变量来访问JSON树。

使用

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 
    }

在JavaScript中了解变量结构。