我正在使用 PHP 和 SQL 生成一个数组,该数组计算具有相同值的数据以及其中有多少值输出 json_encode 到:
{"05":4,"09":4,"19":4}
Chart.js 文件:(精简)
// Chart
var ctx = document.getElementById("monthAbuseChart");
var myLineChart = new Chart(ctx, {
type: 'line',
data: {
labels: ["1", "2", "3"],
datasets: [{
label: "Offences",
//data: [0, 7, 5] This works
data: offences // This doesn't
}],
}
}
});
// Grab the data for offences:
var offences = []
$.ajax({
method: "POST",
url: "sql/monthabuse.php",
dataType : 'json',
success: function (result) {
//offences = result;
var offences = result;
console.log(result);
},
});
console.log 输出 {19: 4, 05: 4, 09: 4}
但是,如果我将 offenses 放入数据部分 data: offences
它不起作用吗?
最佳答案
假设您要填充 AJAX
调用的响应 offences
变量。
您当前的代码有 2 个问题:
在 AJAX 调用运行之前,您创建图表的代码正在运行。在您的代码中,您引用了
offences
变量,但它尚未填充。您已将
offences
定义为全局变量,这没问题。但是在 AJAX 调用中,您再次定义了一个新的局部变量offences
,方法是在它前面加上var
。您需要使用问题中注释的以下代码来填充全局offences
var.
offences = result
解决此问题的一种方法是将您的图表代码包含在新函数中,并在 AJAX 的成功回调中调用此新函数。
//Global Variable
var offences = [];
function createMonthAbuseChart() {
var ctx = document.getElementById("monthAbuseChart");
var myLineChart = new Chart(ctx, {
type: 'line',
data: {
labels: ["1", "2", "3"],
datasets: [{
label: "Offences",
//data: [0, 7, 5] This works
data: offences // This doesn't
}],
}
}
});
}
// Grab the data for offences:
$.ajax({
method: "POST",
url: "sql/monthabuse.php",
dataType : 'json',
success: function (result) {
offences = result;
console.log(result);
createMonthAbuseChart(); //Call the Chart Create Method Here.
},
});
您必须确保 AJAX 调用返回的数据与图表所需的数据格式相同,即 [0, 7, 5]
。从您的问题看来,您的 AJAX 调用正在返回 {19: 4, 05: 4, 09: 4}
。您可以使用以下代码将其转换为[4, 4, 4]
offences = Object.values(result);
在您的 AJAX 回调中使用以上行而不是以下行
offences = result;
关于php - Chartjs 数据通过 json 请求不填充,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57120045/