将数据从数据库导入JS文件

时间:2017-10-17 17:07:05

标签: javascript php mysql

我是.js文件及其使用的新手,我正在尝试更新使用JS的图表。我需要或尝试做的是从我的数据库导入信息,以便在我的JS文件中使用它来填充图表。这是图表代码和文件名。

文件名charjs_custom.js

/*Polar chart*/
    var polarElem = document.getElementById("polarChart");

    var data3 = {
        datasets: [{
            data: [
                20,
                16,
                7,
                3,
                40
            ],
            backgroundColor: [
                "#7E81CB",
                "#1ABC9C",
                "#B8EDF0",
                "#B4C1D7",
                "#01C0C8"
            ],
            hoverBackgroundColor: [
                "#a1a4ec",
                "#2adab7",
                "#a7e7ea",
                "#a5b0c3",
                "#10e6ef"
            ],
            label: 'My dataset' // for legend
        }],
        labels: [
            "Blue",
            "Green",
            "Light Blue",
            "grey",
            "Sea Green"
        ]
    };

    new Chart(polarElem, {
        data: data3,
        type: 'polarArea',
        options: {
            elements: {
                arc: {
                    borderColor: ""
                }
            }
        }
    });

我需要使用来自我的数据库的信息来改变“数据”和“标签”部分,从我所看到的我需要创建一个php文件来检索信息但是我如何将其转换为JS以及如何判断它在JS文件中使用什么信息。还链接“数据”和“标签”部分,以便信息对应于我的表

我想使用的表是:make:id~count

档案名称chart_test.php

<?php

//database
$host="my_host"; // Host name 
$username="my_username"; // Mysql username 
$password="my_password"; // Mysql password 
$db_name="my_database"; // Database name 

//get connection
$mysqli = new mysqli($host, $username, $password, $db_name);

if(!$mysqli){
    die("Connection failed: " . $mysqli->error);
}

//query to get data from the table
$query = sprintf("SELECT * FROM bureau GROUP BY make ");

//execute query
$result = $mysqli->query($query);

//close connection
$mysqli->close();

//now print the data
 print json_encode($data);

 ?>

3 个答案:

答案 0 :(得分:0)

您可以使用JSON格式在php后端和js前端之间交换数据。但是我建议你使用nodejs作为后端服务。它将与您的js代码无缝集成。

答案 1 :(得分:0)

如果不了解您的数据源,通常会像以下一样工作。

<?php
// Lets say your managed to convert your data from your database into something like.
$graph = [
    'data'       => [20, 16, 7, 3, 40],
    'background' => ['#7E81CB', '#1ABC9C', '#B8EDF0', '#B4C1D7', '#01C0C8'],
    'hover'      => ['#a1a4ec', '#2adab7', '#a7e7ea', '#a5b0c3', '#10e6ef'],
    'labels'     => ['Blue', 'Green', 'Light Blue', 'Grey', 'Sea Green']
];

?>

var polarElem = document.getElementById("polarChart");

var data3 = {
    datasets: [{
        data: <?php echo json_encode($graph['data']); ?>,
        backgroundColor: <?php echo json_encode($graph['background']); ?>,
        hoverBackgroundColor: <?php echo json_encode($graph['hover']); ?>,
        label: 'My dataset'
    }],
    labels: <?php echo json_encode($graph['labels']); ?>
};

答案 2 :(得分:0)

因此,如果我理解数据库的映射,我会这样做:

<?php
//database
$host="my_host"; // Host name 
$username="my_username"; // Mysql username 
$password="my_password"; // Mysql password 
$db_name="my_database"; // Database name 

//get connection
$mysqli = new mysqli($host, $username, $password, $db_name);

if(!$mysqli){
    die("Connection failed: " . $mysqli->error);
}

//query to get data from the table
$query = sprintf("SELECT * FROM bureau GROUP BY make ");

//execute query
$result = $mysqli->query($query);


// Define configuration array
$config = array(
   'datasets' => array(
        array(
            'data' => array(),
            'backgroundColor' => array(), // This could be statically loaded, or dynamic if the DB has colors
            'hoverBackgroundColor' => array(), // This could be statically loaded, or dynamic if the DB has colors
            'label' => 'My Dataset'
        )
    ),
    'labels' => array()
);

// Loop through database result and add
while($row=mysqli_fetch_assoc($result)){
    array_push($config['labels'], $row['make']); // Add label
    array_push($config['datasets'][0]['data'], $row['totalValue']); // Add value
}

//close connection
$mysqli->close();

//now print the data
echo json_encode($config);

您最终使用该配置执行的操作取决于您加载此图表的方式。这可能是一个AJAX请求,然后您将使用结果代替data3,例如:

$.get( "chart_test.php", function( data ) {
    new Chart(polarElem, {
        data: data,
        type: 'polarArea',
        options: {
            elements: {
                arc: {
                    borderColor: ""
                }
            }
        }
    });
}, "json" );

或者嵌入到php文件中,这样就可以创建整个脚本而不是打印json_encode($config);

new Chart(polarElem, {
        data: <?= json_encode($config) ?>,
        type: 'polarArea',
        options: {
            elements: {
                arc: {
                    borderColor: ""
                }
            }
        }
    });

这一切都取决于你到目前为止的设置。