我是django和chart js的新手,并试图开发一些项目,但我在尝试将数据从myAPI可视化到chart JS时遇到了一些麻烦,它什么也没显示,以下是我的代码:
var endpoint = '/chart/data/'
var defaultData = []
var labels = [];
$.ajax({
method: "GET",
urls: endpoint,
success: function(data){
labels = data.labels
defaultData = data.default
setChart()
},
error: function(error_data){
console.log("error")
console.log(error_data)
}
})
function setChart(){
var ctxSI = document.getElementById("SumberChart");
var SumberChart = new Chart(ctxSI, {
type: 'bar',
data: {
labels: labels,
datasets: [{
label: '# of Votes',
data: defaultData,
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(153, 102, 255, 0.2)',
'rgba(255, 159, 64, 0.2)'
],
borderColor: [
'rgba(255, 99, 132, 1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255, 1)',
'rgba(255, 159, 64, 1)'
],
borderWidth: 1
}]
},
options: {
scales: {
y: {
beginAtZero: true
}
}
},
});
}
views.py
user = get_user_model()
class ChartData(APIView):
authentication_classes = []
permission_classes = []
def get(self, request, format=None):
labels = ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange']
defaultitem = [12, 19, 3, 5, 2, 3]
data = {
"labels" : labels,
"default" : defaultitem,
}
return Response(data)
home.html
<div class="col-sm-6 col-xl-6">
<div class=" text-center rounded p-4">
<div class="d-flex align-items-center justify-content-center mb-4" >
<h6 class="mb-0 text-center" style="color: black;">Sumber</h6>
</div>
<canvas id="SumberChart" style="color:black ;"></canvas>
</div>
</div>
1条答案
按热度按时间3pmvbmvn1#
您正在返回
Response(data)
。我不知道这是什么类型的响应。最好返回一个JsonResponse。然后在js脚本中,将dataType指定为
json
,或者显式解析数据。