我正在使用Charts.js,其数据和选项来自json中的AJAX请求。当我需要在onComplete
事件上添加回调时,问题就来了,因为JSON应该看起来像
"animation" : {
"onComplete" : function(animation){alert('ok')}
},
这是无效的JSON。
我试图将数据检索为简单文本(datatype: 'text'
),但是当它传递给它时Charts.js我收到一个错误:
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行)。检查一下:Is it valid to define functions in JSON results?
你又忘了在最后关闭花括号。
{
"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
}
}
}
}
}