gpt4 book ai didi

javascript - 来自 mysql、php/JQuery 的 Google 折线图

转载 作者:行者123 更新时间:2023-11-29 21:47:10 26 4
gpt4 key购买 nike

我已经研究了一些程序,现在我需要从 MySQL 获取数据并用 HTML/PHP 显示它。我使用这个 mysql.php 文件从 MySQL 获取数据:

<?php
$hostname = "localhost";
$database = "database";
$username = "username";
$password = "password";
$connect = mysql_connect($hostname, $username, $password)

or die('Could not connect: ' . mysql_error());
$bool = mysql_select_db($database, $connect);
if ($bool === False){
print "can't find $database";
}

$query = "SELECT * FROM `table` ORDER BY timestamp LIMIT 0 , 100";
$result = mysql_query($query) or die("SQL Error 1: " . mysql_error());
// get data and store in a json array
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$values[] = array(
'timestamp' => $row['timestamp'],
'temperature' => $row['temperature'],
);
}

echo json_encode($values);
?>

然后我尝试将其显示到谷歌图表:

<html>
<body>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">

// Load the Visualization API and the piechart package.
google.load('visualization', '1', {'packages':['corechart']});

// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawChart);

function drawChart() {
var jsonData = $.ajax({
url: "http://localhost:8081/xampp/testi/mysql.php",
dataType:"json",
async: false
}).responseText;

// Create our data table out of JSON data loaded from server.
var data = new google.visualization.DataTable(jsonData);

// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, {width: 400, height: 240});
}

</script>
<div id="chart_div"></div>
</body>
</html>

但它只是给出错误:

Open photo

JSON 格式有点不对劲,但是怎么回事呢?

最佳答案

您的 JSON 格式应如下所示

{
"cols": [
{"id":"","label":"Topping","pattern":"","type":"string"},
{"id":"","label":"Slices","pattern":"","type":"number"}
],
"rows": [
{"c":[{"v":"Mushrooms","f":null},{"v":3,"f":null}]},
{"c":[{"v":"Onions","f":null},{"v":1,"f":null}]},
{"c":[{"v":"Olives","f":null},{"v":1,"f":null}]},
{"c":[{"v":"Zucchini","f":null},{"v":1,"f":null}]},
{"c":[{"v":"Pepperoni","f":null},{"v":2,"f":null}]}
]
}

因此,当您尝试将 JSON 转换为 DataTable 时,您不会得到任何返回,因为它的格式不正确。更多内容请阅读此处。

尝试格式化您的 JSON,例如

var jsonData = {}
jsonData.cols = [
{"label":"Date w/ time", "type":"date"},
{"label":"Temp", "type":"number"}
]
jsonData.rows = [
{"c":[{"v":new Date(2015, 11, 1, 12, 23)}, {"v":50}]},
{"c":[{"v":new Date(2015, 11, 1, 12, 24)}, {"v":75}]}
]

关于javascript - 来自 mysql、php/JQuery 的 Google 折线图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34019009/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com