我正在尝试使用动态数据构建Morris Donut图表,但似乎无法理解如何传递标签的动态数据。
SQLi
dB方法查询:
get_requests_count_per_ouc_per_month($month){
$connection = get_db();
$query = "SELECT U.ouc AS ouc, COUNT(R.engineer_uin) AS no_of_requests
FROM users AS U
INNER JOIN request AS R ON R.engineer_uin = U.uin
AND EXTRACT(MONTH FROM R.date_received) =".$month."
GROUP BY U.ouc
ORDER BY no_of_requests";
return $connection->query($query);
}
查询返回以下结果:
ouc | no_of_requests
BVG15 | 1
BVG16 | 2
BVG13 | 4
BVG1C3 | 5
我希望将{ouc作为labels
和no_of_requests传递为ykeys
:
所以我的圆环图应该是这样的:
donut_chart_pct = Morris.Donut({
element: 'donut_chart_pct',
data: [
{label: "BVG15", value: 1},
{label: "BVG16", value: 2},
{label: "BVG13", value: 4},
{label: "BVG1C3", value: 5}
],
});
但是,我不知道将返回多少ouc
因此Label
必须是动态的,即缩小/扩展,具体取决于返回的唯一OUC's
的数量以及他们各自的counts
这就是我的尝试:
function prepare_donut_chart_requests_per_ouc_org_data(){
//$returnArray=array();
$month = date('m', strtotime(date('Y-m-01')));
$requests = get_requests_count_per_ouc_per_month($month);
while($row = $requests->fetch_assoc()) {
$returnArray[]=array('ouc'=>$row['ouc'],'total'=>$row['no_of_requests']);
}
return $returnArray;
}
$returnArray = prepare_donut_chart_requests_per_ouc_org_data();
http_response_code(200);
echo json_encode($returnArray);
以json格式返回以下数组:
[{"ouc":"BVG15","total":"1"},{"ouc":"BVG16","total":"2"},{"ouc":"BVG13","total":"4"},{"ouc":"BVG1C3","total":"5"}]
现在我不知道如何使用相应的值设置我的圆环图标签,因为我不知道如何动态传递它?
我的JavaScript看起来像这样:
function add_donut_chart_requests_per_ouc_org_data(){
$.ajax({
type:"GET",
url:"graph-calls.php",
dataType:"json",
contentType:"application/json",
data:"chart=donut_chart_requests_per_ouc_org",
success:function(response){
reload_chart('donut_chart_requests_per_ouc_org',response);
console.log(JSON.stringify(response));
},
error: function(response){
alert('there was an error!' + JSON.stringify(response));
}
});
return false;
}
function reload_chart(chart,response){
if(chart=='donut_chart_requests_per_ouc_org'){
if(response!=null){
var ouc= response.ouc;
var total= response.total;
var donut_chart_data = [
{label: ouc, value: total}
];
donut_chart_requests_per_ouc_org.setData(donut_chart_data);
donut_chart_requests_per_ouc_org.redraw();
}
}
}
问题是我似乎无法获得ouc
和total
值。如果我打印出来就说undefined
。我究竟做错了什么? :/任何代码示例都将受到高度赞赏
更新
对我的javascript reload
方法进行了以下更改,现在它正在运行:
if(chart=='donut_chart_requests_per_ouc_org'){
donut_chart_data=[];
for(var i=0; i<response.length;i++){
var ouc= response[i].ouc;
var total= response[i].total;
donut_chart_data[i]={label:ouc,
value:total
};
}
console.log(donut_chart_data);
if(donut_chart_data.length){
donut_chart_requests_per_ouc_org.setData(donut_chart_data);
donut_chart_requests_per_ouc_org.redraw();
}
}