gpt4 book ai didi

javascript - Php/ajax 以与 javascript 数组相同的形式返回 JSON

转载 作者:行者123 更新时间:2023-12-03 10:02:48 24 4
gpt4 key购买 nike

我正在使用charts.js插件来创建图表。它使用 JavaScript 数组 data 来生成图表。

var data = {
labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: [
{
label: "My First dataset",
fillColor: "rgba(220,220,220,0.2)",
strokeColor: "rgba(220,220,220,1)",
pointColor: "rgba(220,220,220,1)",
pointStrokeColor: "#fff",
pointHighlightFill: "#fff",
pointHighlightStroke: "rgba(220,220,220,1)",
data: [65, 59, 80, 81, 56, 55, 40]
},
{
label: "My Second dataset",
fillColor: "rgba(151,187,205,0.2)",
strokeColor: "rgba(151,187,205,1)",
pointColor: "rgba(151,187,205,1)",
pointStrokeColor: "#fff",
pointHighlightFill: "#fff",
pointHighlightStroke: "rgba(151,187,205,1)",
data: [28, 48, 40, 19, 86, 27, 90]
}
]
};

我想使用ajax返回不同时间范围的结果。我如何使用 php 生成响应,以便当我在 ajax 中成功读取它时,我可以像使用 var data 生成初始图表一样使用它。

        $.ajax('/chart.php', {
type: 'POST',
data: {range: range},
dataType: 'json',
success: function(data) {
console.log(data);
}
});

最佳答案

您想要的是创建一个对象数组,然后使用 json_encode它应该会产生你需要的东西。试试这个:

$array = array();
$dataset = new stdClass;
$dataset->label = "My first dataset";
// repeat for each field
$array[] = $dataset;
echo json_encode($array);

我们可以做的就是缩短这个时间,而不是每次都声明一个新的数据集 use an array and typecast it to an object像这样:

$datasets = array();
$datasets[] = (object) array(
'label' => "My First dataset",
'fillColor' => "rgba(220,220,220,0.2)",
'strokeColor' => "rgba(220,220,220,1)",
'pointColor' => "rgba(220,220,220,1)",
'pointStrokeColor' => "#fff",
'pointHighlightFill' => "#fff",
'pointHighlightStroke' => "rgba(220,220,220,1)",
'data' => [65, 59, 80, 81, 56, 55, 40]
);

Check out this eval.in一个工作示例。

更新

对于完整的结构,您需要:

$data = (object) [
'labels' => ["January", "February", "March", "April", "May", "June", "July"],
datasets => []
];

$data->datasets[] = (object) [
'label' => "My First dataset",
'fillColor' => "rgba(220,220,220,0.2)",
'strokeColor' => "rgba(220,220,220,1)",
'pointColor' => "rgba(220,220,220,1)",
'pointStrokeColor' => "#fff",
'pointHighlightFill' => "#fff",
'pointHighlightStroke' => "rgba(220,220,220,1)",
'data' => [65, 59, 80, 81, 56, 55, 40]
];

echo json_encode($data);

关于javascript - Php/ajax 以与 javascript 数组相同的形式返回 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30503803/

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