json - Charts.js - 来自 JSON 的 onComplete javascript 函数
问题描述
我正在将 Charts.js 与来自 json 中的 AJAX 请求的数据和选项一起使用。当我需要添加onComplete
事件回调作为选项时,问题就出现了,因为 JSON 应该看起来像
"animation" : {
"onComplete" : function(animation){alert('ok')}
},
这不是有效的 JSON。
我尝试将数据检索为简单文本datatype: 'text'
(
Uncaught TypeError: Cannot create property 'data' on string
这可能是我正在检索的 json
{
"type" : "line",
"data" : {
"datasets" : [ {
"data" : [ {
"t" : 1551096300000,
"y" : 22.8125
}, {
"t" : 1551096600000,
"y" : 22.8125
}, {
"t" : 1551096900000,
"y" : 22.8125
}, {
"t" : 1551097200000,
"y" : 22.8125
}, {
"t" : 1551097500000,
"y" : 22.8125
}, {
"t" : 1551097800000,
"y" : 19.3125
}],
"label" : "Sample data",
"fill" : false,
"backgroundColor" : "rgba(0,128,0,1.000)",
"borderWidth" : 2,
"borderColor" : "rgba(0,128,0,1.000)"
},
"options" : {
"responsive" : true,
"maintainAspectRatio" : true,
"title" : {
"display" : true,
"position" : "top",
"text" : "Temperature (°C)"
},
"legend" : {
"position" : "bottom"
},
"hover" : {
"mode" : "dataset"
},
"animation" : {
"onComplete" : function(animation){alert('ok')}
},
"scales" : {
"xAxes" : [ {
"type" : "time",
"time" : {
"displayFormats" : {
"millisecond" : null,
"second" : null,
"minute" : "HH:mm",
"hour" : "DD/MM HH:mm",
"day" : "DD/MM HH:mm",
"week" : null,
"month" : "DD/MM HH",
"quarter" : null,
"year" : null
},
"tooltipFormat" : "DD/MM/YY HH:mm"
}
} ]
},
"elements" : {
"point" : {
"radius" : 1,
"hitRadius" : 2,
"hoverRadius" : 2
}
}
}
}
解决方案
首先,您忘记在第 29 行关闭数据集数组。
其次,在 JSON 结果中定义函数是无效的(第 45 行)。 检查一下:在 JSON 结果中定义函数是否有效?
你又忘了在最后关闭花括号。
{
"type": "line",
"data": {
"datasets": [{
"data": [{
"t": 1551096300000,
"y": 22.8125
}, {
"t": 1551096600000,
"y": 22.8125
}, {
"t": 1551096900000,
"y": 22.8125
}, {
"t": 1551097200000,
"y": 22.8125
}, {
"t": 1551097500000,
"y": 22.8125
}, {
"t": 1551097800000,
"y": 19.3125
}],
"label": "Sample data",
"fill": false,
"backgroundColor": "rgba(0,128,0,1.000)",
"borderWidth": 2,
"borderColor": "rgba(0,128,0,1.000)"
}],
"options": {
"responsive": true,
"maintainAspectRatio": true,
"title": {
"display": true,
"position": "top",
"text": "Temperature (°C)"
},
"legend": {
"position": "bottom"
},
"hover": {
"mode": "dataset"
},
"animation": {
"onComplete": ""
},
"scales": {
"xAxes": [{
"type": "time",
"time": {
"displayFormats": {
"millisecond": null,
"second": null,
"minute": "HH:mm",
"hour": "DD/MM HH:mm",
"day": "DD/MM HH:mm",
"week": null,
"month": "DD/MM HH",
"quarter": null,
"year": null
},
"tooltipFormat": "DD/MM/YY HH:mm"
}
}]
},
"elements": {
"point": {
"radius": 1,
"hitRadius": 2,
"hoverRadius": 2
}
}
}
}
}
推荐阅读
- reactjs - React Fetch API 无法渲染图像
- javascript - 为什么我收到“错误:发送后无法设置标头。”?
- locust - 对于 Locust 的负载测试,每个 locust 用户能否可靠地每 x 秒发送一次请求?
- php - 项目缺少锁定文件时如何安装新的 Laravel 包而不更新其他包
- html - 我们可以自定义选择选项表单吗?
- java - 尽可能动态地(许多不同的格式)从 .csv 文件中解析日期或日期时间字符串?
- visual-studio-code - 在 Visual Studio Code 中更改标题栏和状态栏中的图标颜色
- python - 事务未按预期工作 SQLAlchemy
- android - cmake 何时不为链接目录生成“-L”标志?
- docker - Docker - 单个节点群中的堆栈间网络问题