gpt4 book ai didi

javascript - 拆分 JSON 响应并使用图表数据

转载 作者:行者123 更新时间:2023-12-01 03:38:44 25 4
gpt4 key购买 nike

我使用 jQuery/AJAX 从 PHP 后端接收 JSON 格式的响应,格式如下:

{"result":[["Cellphone","900"],["Medical","900"],["Repair and Maintenance","3700"],["Travel","867.2"]],"errors":false}

这就是我从 PHP 后端生成 JSON 的方式:

    $addresult = "
SELECT category,SUM(receiptamount)
FROM scans
GROUP BY category;
";

if( $result = $mysqli->query($addresult) ) {
// collect results
while($row = $result->fetch_all())
{
// assign to new array
// make returnResult an array for multiple results
$returnResult = $row;
}
}

...
echo json_encode(['result' => $returnResult, 'errors' => $errors]);

这是我的 jQuery/AJAX 成功 函数:

success: function(response) {
if(!response.errors && response.result) {

var str = (response.result[1]).toString();
var str_array = str.split(',');
for(var i = 0; i < str_array.length; i++) {
str_array[i] = str_array[i].replace(/^\s*/, "").replace(/\s*$/, "");
//alert(str_array[i]);
}
var chart = c3.generate({
bindto: document.getElementById('chart'),
data: {
columns: [
['Travel', 30],
['Accommodation', 130],
['Cellphone', 130],
['Donation', 130],
['Gift', 130],
['Medical', 130],
['Repair and Maintenance', 130],
['Other Expense', 130]
],
type: 'bar'
},
bar: {
width: {
ratio: 0.5 // this makes bar width 50% of length between ticks
}
}
});

} else {
myApp.alert('Something went wrong', 'Oops!');
}
}

我想根据这些数据生成图表列名称和相应的金额,但我不知道如何生成。

最佳答案

看起来你可以简单地改变这个:

data: {
columns: [
['Travel', 30],
['Accommodation', 130],
['Cellphone', 130],
['Donation', 130],
['Gift', 130],
['Medical', 130],
['Repair and Maintenance', 130],
['Other Expense', 130]
],
type: 'bar'
},

对此:

data: {
columns: response.result,
type: 'bar'
},

关于javascript - 拆分 JSON 响应并使用图表数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44054770/

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