整合Chart.js与Django(数据未显示)

ehxuflar  于 2022-11-06  发布在  Chart.js
关注(0)|答案(1)|浏览(137)

我是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>

附页:My Html
附页:API
这是我第一次摆姿势,我真的很感激任何解决我问题的想法,谢谢。

3pmvbmvn

3pmvbmvn1#

您正在返回Response(data)。我不知道这是什么类型的响应。最好返回一个JsonResponse。

from django.http import JsonReponse
class ChartData(APIView):
    # your code
    def get(self, request, format=None):
        # your code
        return JsonResponse(data)

然后在js脚本中,将dataType指定为json,或者显式解析数据。

// Specify the dataType as json
$.ajax({
    method: "GET",
    urls: endpoint,
    dataType: "json",
    // rest of your code
});

// Explicitly parse data
$.ajax({
    success: function(data){
        jsonData = JSON.parse(data);
        labels = jsonData.labels;
        defaultData = jsonData.default;
        setChart();
    },
    // rest of your code
});

相关问题