简体   繁体   English

D3从mysql获取JSON数据总是返回未定义

[英]D3 get JSON data from mysql always returning undefined

I have done a lot R&D, tried lots of question on stackoverflow and from other site too but unable to understand what i am doing wrong. 我做了很多研发工作,在stackoverflow和其他站点上也尝试了很多问题,但是无法理解我在做什么错。 I will be really thankful if help me to point where i am wrong. 如果能帮助我指出错误之处,我将非常感激。

Also tried this too if code is skipping before response but not use. 如果代码在响应之前跳过但未使用,也可以尝试此操作。 Returning array from d3.json() 从d3.json()返回数组

D3 code D3代码

<!DOCTYPE html>
<meta charset="utf-8">
<body>
<script src="http://d3js.org/d3.v3.min.js"></script>
<script>
    d3.json("chart_data.php", function(error, data){
        json_Data = data;
        console.log("Error:"+error);
        console.log(json_Data);
    });
</script>
</body>
</html>

Console for error is 错误控制台是

Error:SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data

Console for data is 数据控制台为

undefined

If I run php file direct in browser I am getting: 如果我直接在浏览器中运行php文件,我将得到:

[{"value":"1","date":"2016-03-29"},{"value":"0","date":"2016-03-30"},{"value":"3","date":"2016-03-31"},{"value":"2","date":"2016-04-01"},{"value":"2","date":"2016-04-02"},{"value":"5","date":"2016-04-03"},{"value":"1","date":"2016-04-04"},{"value":"1","date":"2016-04-05"},{"value":"0","date":"2016-04-06"}]

This is my PHP 这是我的PHP

<?php
require 'db_connection.php';
$sql = "SELECT `y-axis` as value, `x-axis` as date FROM site_data";
$result = $con->query($sql);
$data = array();
if ($result->num_rows > 0) {
    $count = 0;
    while($row = $result->fetch_assoc()) {
        $data[$count]['value'] = $row['value'];
        $data[$count]['date']  = $row['date'];
        $count++;
    }
}
echo json_encode($data);
$con->close();
?>

DB connection file 数据库连接文件

<?php
$con = mysqli_connect("localhost","root","","analytic");
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }
?>

PHP file and D3 file is on same directory. PHP文件和D3文件位于同一目录中。

Instead of passing a .php file as a parameter to d3.json() try passing a .json file: 而不是将.php文件作为参数传递给d3.json(),请尝试传递.json文件:

d3.json("chart_data.json", function(error, data){
    json_Data = data;
    console.log("Error:"+error);
    console.log(json_Data);
});

Use php to get the code from the DB and convert it to json using something like json_encode . 使用php从数据库获取代码,并使用json_encode类的代码将其转换为json。 Output that data in a .json file. 在.json文件中输出该数据。 Don't try to read json directly from a .php file. 不要尝试直接从.php文件读取json。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM