我已经创建了一个MySQL数据库,并且正在本地运行xampp。
这是我的data.php:
<?php
//setting header to json
header('Content-Type: application/json');
//database
define('DB_HOST', 'localhost');
define('DB_USERNAME', 'root');
define('DB_PASSWORD', '');
define('DB_NAME', 'products');
//get connection
$mysqli = new mysqli(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_NAME);
if(!$mysqli){
die("Connection failed: " . $mysqli->error);
}
//query to get data from the table
$query = sprintf("SELECT date, url, price FROM table1");
//execute query
$result = $mysqli->query($query);
//loop through the returned data
$data = array();
foreach ($result as $row) {
$data[] = $row;
}
//free memory associated with result
$result->close();
//close connection
$mysqli->close();
//now print the data
print json_encode($data);
输出文件生成日期,价格和网址
当我查看一下barchart.html时,我试图引入一个onclick链接,当用户单击每个栏时指向URL。
$(document).ready(function(){
$.ajax({
url: "http://192.168.64.2/fs/data.php",
method: "GET",
success: function(data) {
console.log(data);
var date = [];
var price = [];
for(var i in data) {
date.push("" + data[i].date);
price.push(data[i].price);
}
var chartdata = {
labels: date,
datasets : [
{
label: 'price',
backgroundColor: 'rgba(200, 200, 200, 0.75)',
borderColor: 'rgba(200, 200, 200, 0.75)',
hoverBackgroundColor: 'rgba(200, 200, 200, 1)',
hoverBorderColor: 'rgba(200, 200, 200, 1)',
data: price,
}
]
};
var ctx = $("#mycanvas");
var barGraph = new Chart(ctx, {
type: 'bar',
data: chartdata
});
},
error: function(data) {
console.log(data);
}
});
});
这是生成的条形图;
当我将鼠标悬停在条形图上时,会显示日期和价格,但是单击时,我想将用户重定向到url,就像从data.php中的table1中提取的一样