Chart.js update() Ajax 更新表單資料方法範例

5 月 17, 2018 | | 0 條留言

使用update()函數經過AJAX方法更新表單。

var ajaxCallLiveSubs = function(){

    // endopoint
    var url = 'https://jsonplaceholder.typicode.com/posts/1';

    var interval = 5000;

    var time = 0;

    // Live Subs Charts
    var ctx_live = document.getElementById("myChart");

    var liveChart = new Chart(ctx_live, {
        type: 'line',
        data: {
            labels: [],
            datasets: [{
                data: [],
                borderWidth: 1,
                borderColor:'#00c0ef',
                label: 'liveCount',
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            legend: {
                display: false
            },
            scales: {
                yAxes: [{
                    ticks: {
                        beginAtZero:true,
                    }
                }]
            }
        }
    });

    var doAjax = function() {

        $.ajax({
                    url: url,
                    success: function(){
                        var currentTime = ++time
                        var currentValue = Math.random()*1000;
                        liveChart.data.labels.push(currentTime);
                        liveChart.data.datasets[0].data.push(currentValue);

                        liveChart.update();

                    },
                    complete: function () {
                            // Schedule the next
                            setTimeout(doAjax, interval);
                    }
                });
    };

    doAjax();

};

ajaxCallLiveSubs();