首页 > 解决方案 > 在 Ajax 中分离数据列表

问题描述

我有一个列表,其中包含来自 Ajax 函数调用的 python 脚本的 4 个数据。我无法弄清楚分离它的方法。我需要将其分开的原因是因为每个数据将被发送到单独的 Chartjs 进行显示。现有的 ajax 函数从 python 脚本中的单独函数获取单个数据,我想用最新的 ajax 和 python 脚本替换它们。

这是我的html页面功能:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8"/>
    <title>Chart.js demo</title>
    <!-- import plugin script -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.27.0/moment.min.js"
            integrity="sha512-rmZcZsyhe0/MAjquhTgiUcb4d9knaFc7b5xAfju483gbEXTkeJRUMIPk6s3ySZMYUHEcjKbjLjyddGWMrNEvZg=="
            crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/chart.js@2.8.0"></script>
    <script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-streaming@latest/dist/chartjs-plugin-streaming.min.js"></script>

</head>
<body>


<div style="height: 450px; width: 450px; display: inline-block">
    <canvas id="myChart" width="450" height="450"></canvas>
</div>

<div style="height: 450px; width: 450px; display: inline-block">
    <canvas id="myChart2" width="450" height="450"></canvas>
</div>

<div style="height: 450px; width: 450px; display: inline-block">
    <canvas id="myChart4" width="450" height="450"></canvas>
</div>

<div style="height: 450px; width: 450px; display: inline-block">
    <canvas id="myChart5" width="450" height="450"></canvas>
</div>

<div style="height: 450px; width: 450px; display: inline-block">
    <canvas id="myChart3" width="450" height="450"></canvas>
</div>

<script>
    //the ajax function I want to use
    function monitor() {
        var xhttp = new XMLHttpRequest();

        xhttp.onreadystatechange = function () {
            if (this.readyState == 4 && this.status == 200) {
                data = this.responseText;

                chart.config.data.datasets.forEach(function (dataset) {
                    dataset.data.push({
                        x: Date.now(),
                        y: data,
                    });
                });
            }

        };

        xhttp.open("GET", "getmonitor", true);
        xhttp.send();

        return disp;
    }
</script>

<script>
    //the existing ajax
    function cpuDoc() {
        var xhttp = new XMLHttpRequest();

        var disp = {x: Date.now(), y: 25.7};


        xhttp.onreadystatechange = function () {
            if (this.readyState == 4 && this.status == 200) {
                cp = this.responseText;

                chart.config.data.datasets.forEach(function (dataset) {
                    dataset.data.push({
                        x: Date.now(),
                        y: cp,
                    });
                });
            }

        };

        xhttp.open("GET", "getcpu", true);
        xhttp.send();

        return disp;
    }


    var ctx = document.getElementById('myChart').getContext('2d');
    var chart = new Chart(ctx, {
        type: 'line',
        data: {
            datasets:
                [{
                    label: "CPU Percentage",
                    data: [],
                    borderColor: "#d7041c",
                    fill: false
                }]
        },
        options: {
            legend: {
                display: true,
                fill: true
            },
            title: {
                display: true,
                text: 'CPU'
            },
            scales: {
                xAxes: [{
                    scaleLabel: {
                        display: true,
                        labelString: 'Time'
                    },
                    type: 'realtime',
                    realtime: {
                        duration: 10000,
                        delay: 10000,
                        refresh: 1000,
                        onRefresh: memoryDoc()
                    }
                }],
                yAxes: [{
                    display: true,
                    ticks: {
                        beginAtZero: true,
                        steps: 20,
                        max: 100,
                    },
                    scaleLabel: {
                        display: true,
                        labelString: 'Percentage'
                    }
                }]
            }
        }
    });
</script>


<script>
    //the existing ajax
    function memoryDoc() {
        var xhttp = new XMLHttpRequest();

        var disp = {x: Date.now(), y: 25.7};

        xhttp.open("GET", "getmem", true);
        xhttp.send();
        xhttp.onreadystatechange = function () {
            if (this.readyState == 4 && this.status == 200) {
                mm = this.responseText;


                chart2.config.data.datasets.forEach(function (dataset) {
                    dataset.data.push({
                        x: Date.now(),
                        y: mm,
                    });
                });
            }

        };

        return disp;
    }


    var ctx = document.getElementById('myChart2').getContext('2d');
    var chart2 = new Chart(ctx, {
        type: 'line',
        data: {
            datasets:
                [{
                    label: "Memory Percentage",
                    data: [],
                    borderColor: "#0a2dae",
                    fill: false
                }]
        },
        options: {
            title: {
                display: true,
                text: 'Memory'
            },
            scales: {
                xAxes: [{
                    scaleLabel: {
                        display: true,
                        labelString: 'Time'
                    },
                    type: 'realtime',
                    realtime: {
                        duration: 10000,
                        delay: 10000,
                        refresh: 1000,
                        onRefresh: memoryDoc
                    },
                }],
                yAxes: [{
                    display: true,
                    ticks: {
                        beginAtZero: true,
                        steps: 20,
                        max: 100,
                    },
                    scaleLabel: {
                        display: true,
                        labelString: 'Percentage'
                    }
                }]
            }
        }
    });
</script>

<script>
    //the existing ajax
    function networkIn() {
        var xhttp = new XMLHttpRequest();
        var disp = {x: Date.now(), y: 25.7};

        xhttp.open("GET", "getib", true);
        xhttp.send();
        xhttp.onreadystatechange = function () {
            if (this.readyState == 4 && this.status == 200) {
                ib = this.responseText;


                chart4.config.data.datasets.forEach(function (dataset) {
                    dataset.data.push({
                        x: Date.now(),
                        y: ib,
                    });
                });
            }

        };

        return disp;
    }

    var ctx = document.getElementById('myChart4').getContext('2d');
    var chart4 = new Chart(ctx, {
        type: 'line',
        data: {
            datasets:
                [{
                    label: "Inbound",
                    data: [],
                    borderColor: "#d7c204",
                    fill: false
                }]
        },
        options: {
            legend: {
                display: true,
            },
            title: {
                display: true,
                text: 'Network Usage'
            },
            scales: {
                xAxes: [{
                    scaleLabel: {
                        display: true,
                        labelString: 'Time'
                    },
                    type: 'realtime',
                    realtime: {
                        duration: 10000,
                        delay: 10000,
                        refresh: 1000,
                        onRefresh: networkIn
                    }
                }],
                yAxes: [{
                    display: true,
                    ticks: {
                        beginAtZero: true,
                        steps: 20,
                        max: 100,
                    },
                    scaleLabel: {
                        display: true,
                        labelString: 'MBPS'
                    }
                }]
            }
        }
    });
</script>


<script>
    //the existing ajax
    function networkOut() {
        var xhttp = new XMLHttpRequest();
        var disp = {x: Date.now(), y: 25.7};

        xhttp.open("GET", "getob", true);
        xhttp.send();
        xhttp.onreadystatechange = function () {
            if (this.readyState == 4 && this.status == 200) {
                ob = this.responseText;


                chart5.config.data.datasets.forEach(function (dataset) {
                    dataset.data.push({
                        x: Date.now(),
                        y: ob,
                    });
                });
            }

        };

        return disp;
    }


    var ctx = document.getElementById('myChart5').getContext('2d');
    var chart5 = new Chart(ctx, {
        type: 'line',
        data: {
            datasets:
                [{
                    label: "Outbound",
                    data: [],
                    borderColor: "#5fd913",
                    fill: false
                }]
        },
        options: {
            legend: {
                display: true,
            },
            title: {
                display: true,
                text: 'Network Usage'
            },
            scales: {
                xAxes: [{
                    scaleLabel: {
                        display: true,
                        labelString: 'Time'
                    },
                    type: 'realtime',
                    realtime: {
                        duration: 10000,
                        delay: 10000,
                        refresh: 1000,
                        onRefresh: networkOut
                    }
                }],
                yAxes: [{
                    display: true,
                    ticks: {
                        beginAtZero: true,
                        steps: 20,
                        max: 100,
                    },
                    scaleLabel: {
                        display: true,
                        labelString: 'MBPS'
                    }
                }]
            }
        }
    });
</script>


<script>
    //the existing ajax
    setInterval(loadDoc3, 900000)

    function loadDoc3() {

        var xhttp = new XMLHttpRequest();
        xhttp.open("GET", "getdk", true);
        xhttp.send();
        xhttp.onreadystatechange = function () {
            if (this.readyState == 4 && this.status == 200) {
                dk = this.responseText;

            }
        };

        var xhttp = new XMLHttpRequest();
        xhttp.open("GET", "getdkf", true);
        xhttp.send();
        xhttp.onreadystatechange = function () {
            if (this.readyState == 4 && this.status == 200) {
                dkf = this.responseText;

            }
        };

        dss = [dk, dkf];

        chart3.data.datasets.pop({
            data: dss
        });
        chart3.update();

        chart3.data.datasets.push({
            data: dss
        });
        chart3.update();


    }

    var ctx = document.getElementById('myChart3').getContext('2d');
    var chart3 = new Chart(ctx, {
        type: 'pie',
        data: {
            labels: ["Used", "Free"],
            datasets: [{
                label: "Disk Usage",
                backgroundColor: ["#8a0404", "#177000"],
                data: [0, 0],
            }]
        },
        options: {
            title: {
                display: true,
                text: 'Disk Usage'
            },
            elements: {
                arc: {
                    backgroundColor: ["#8a0404", "#177000"]
                }
            },
        },

    });
</script>

</body>
</html>

get 监视器从 views.py 中返回数据列表,如下所示:


# load html page to display Chartjs
def cpu_monitor(request):
    # execute the call function upon loading chart.html
    # call()

    return render(request, "chart.html")


# gather data from Flask for cpu, memory and network usage
def monitor(request):
    # request data from Flask
    url1 = "http://127.0.0.1:5000/cpu"
    url2 = "http://127.0.0.1:5000/memory"
    url3 = "http://127.0.0.1:5000/inb"
    url4 = "http://127.0.0.1:5000/oub"

    # storing received data
    cpu_data = requests.get(url1)
    memory_data = requests.get(url2)
    ib_data = requests.get(url3)
    ob_data = requests.get(url4)

    # converting stored data to json format
    cpu_data2 = cpu_data.json()
    memory_data2 = memory_data.json()
    ib_data2 = ib_data.json()
    ob_data2 = ob_data.json()

    # extracting only the value of the received data
    for key in cpu_data2:
        cpu_value = cpu_data2['CPU']
        time = cpu_data2['Time']
        print(cpu_value)
        print(time)

    for key in memory_data2:
        memory_value = memory_data2['Memory Percentage']
        time = memory_data2['Time']
        print(memory_value)
        print(time)

    for key in ib_data2:
        inbound_value = ib_data2['Received Bytes']
        time = ib_data2['Time']
        print(inbound_value)
        print(time)

    for key in ob_data2:
        outbound_value = ob_data2['Received Bytes']
        time = ob_data2['Time']
        print(outbound_value)
        print(time)

    # storing the extracted values into dictionary
    monitorData = [cpu_value, memory_value, inbound_value, outbound_value]

    # returning the dictionary
    return HttpResponse(monitorData)

标签: javascriptpythonajaxchart.js

解决方案


您需要将图表作为单独的实体:

// Put all the instances of Chart into a single array
let charts = [chart1, chart2, ... ]

// when the data comes back, do the following:
let data = [80, 70, ... ] // example data

data.map((value, index) => {
   let chart = charts[index];
   // assign data to chart
   chart.data = value;
})

推荐阅读