Javascript 如何以plottable格式输出PHP结果
我试图用它来绘制Javascript 如何以plottable格式输出PHP结果,javascript,php,mysql,d3.js,plotly,Javascript,Php,Mysql,D3.js,Plotly,我试图用它来绘制PHP从MySQL数据库的输出。我需要像这样格式化输出- var data = [ { x: ['giraffes', 'orangutans', 'monkeys'], y: [20, 14, 23], type: 'bar' } ]; Array ( [0] => 20 [1] => 14 [2] => 23 ) $rows = array(); while($query_result = $re
PHP
从MySQL
数据库的输出。我需要像这样格式化输出-
var data = [
{
x: ['giraffes', 'orangutans', 'monkeys'],
y: [20, 14, 23],
type: 'bar'
}
];
Array
(
[0] => 20
[1] => 14
[2] => 23
)
$rows = array();
while($query_result = $result->fetch_assoc()) {
$rows[] = $query_result;
}
echo json_encode($rows);
这是我目前用来获取输出的代码-
#PHP
$x = array();
$y = array();
while($query_result = $result->fetch_assoc()) {
$x[] = $query_result['Animal'];
$y[] = $query_result['Count'];
}
print_r($y);
#Javascript
$.get('../assets/php/Animals.php', function(data) {
Plotly.newPlot('AnimalChart', data);
});
但它会像这样返回数据-
var data = [
{
x: ['giraffes', 'orangutans', 'monkeys'],
y: [20, 14, 23],
type: 'bar'
}
];
Array
(
[0] => 20
[1] => 14
[2] => 23
)
$rows = array();
while($query_result = $result->fetch_assoc()) {
$rows[] = $query_result;
}
echo json_encode($rows);
我也尝试过像这样json\u编码
-
var data = [
{
x: ['giraffes', 'orangutans', 'monkeys'],
y: [20, 14, 23],
type: 'bar'
}
];
Array
(
[0] => 20
[1] => 14
[2] => 23
)
$rows = array();
while($query_result = $result->fetch_assoc()) {
$rows[] = $query_result;
}
echo json_encode($rows);
但输出是这样的,与绘图的预期格式不匹配-
[{"Animal":"giraffes","Count":"20"},
{"Animal":"orangutans","Count":"14"},
{"Animal":"monkeys","Count":"23"}]
在这两种情况下,Plot.ly
返回一个错误,这就是为什么我认为它需要像第一个示例那样格式化
未捕获类型错误:无法读取未定义的属性“selectAll”
您的数据不仅仅是
$x
,您还需要以下内容:
$x = array();
$y = array();
while($query_result = $result->fetch_assoc()) {
$x[] = $query_result['Animal'];
$y[] = $query_result['Count'];
}
$data = [ [
"x" => $x,
"y" => $y,
"type" => "bar"
] ];
echo json_encode($data);
您的JS还需要使用正确的数据类型:
$.get('../assets/php/Animals.php', null, function(data) {
Plotly.newPlot('AnimalChart', data);
}, "json");
JS中“null”的用途是什么?接受4个参数,
url[,data][,success][,dataType]
我知道jQuery通常很聪明,可以根据它们的值推断您发送的参数,但我希望更明确一些,以便100%确定null
对应于PHP脚本不需要的data
参数。