簡體   English   中英

“未捕獲的ReferenceError:圖表未定義”

[英]“Uncaught ReferenceError: chart is not defined”

所有,

我正在使用以下HTML / Javascript代碼:

<!doctype html>
<html>
<head>
    <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <!-- google fonts from CDN -->
    <link href='http://fonts.googleapis.com/css?family=Open+Sans:400,300,600' rel='stylesheet' type='text/css'>
    <!-- highcharts -->
    <script src="http://code.highcharts.com/highcharts.js"></script>

    <style>
        html, body {
            width: 95%;
            margin: auto;
            font-family: 'Open Sans',sans-serif;
        }
        #chart_container {
            width:100%;
            height:500px;
        }
    </style>
</head>
<body>
    <h1>Live Data</h1>
    <div id="chart_container">

    </div>
</body>
<script type="text/javascript">
    $(document).ready(function() {
        chart = new Highcharts.Chart({
            chart: {
                renderTo: 'chart_container',
                defaultSeriesType: 'line',
                events: {
                    load: getBirds
                }
            },
            title: {
                text: 'DRHW Live Data Stream'
            },
            xAxis: {
                type: 'datetime',
                tickPixelInterval: 150,
                maxZoom: 20 * 1000
            },
            yAxis: {
                title: {
                    text: 'Count Observed'
                }
            },
            series: [
            ],
            legend: {
                layout: 'horiztonal',
                align: 'center'
            }
        });
        function getBirds() {
            var now = new Date();
            var et = now.getTime() / 1000; //PHP TS
            var st = et - 10; //30 seconds prior in PHP
            console.log(chart);
            if (chart.series.length > 0) {
                var series = chart.series[0];
                var length = series.length + 1;
                var shift = series.data.length > 20;
            }
            $.getJSON("https://path/to/json&callback=?", function(result) {
                var data = result.data;if (data.length == 0) {
                    return;
                } else {
                    additions = new Array();
                    for (i=0;i<data.length;i++) {
                        if (data[i].qstype != "1") {
                            species = data[i].answers[0]['answer'];
                            scode = species.substring(0,species.search(" - ")).trim()
                            count = (data[i].answers[1]['answer'] * 1);
                            newdata = new Object();
                            newdata['name'] = species;
                            newdata['count'] = count;
                            additions.push(newdata);
                        }
                    }
                    //now, for each addition, you need to loop through the existing data structures, and see if the thing exists.  if it does, add the data; if not, add the thing, then add the data.
                    var existingdata = chart.series;
                    for (i=0;i<additions.length;i++) {
                        isnewpoint = true;
                        for (j=0;j<existingdata.length;j++) {
                            if (existingdata[j].name == additions[i].name) {
                                isnewpoint = false
                                count = additions[i].count;
                                point = [now.getTime(),count];
                                chart.series[j].addPoint(point, true, shift);
                                shift = false; //this way, only one shift occurs - the first time through adding a new point to an existing data set. this will control against future shifting, either from other datapoints having new points added, 
                            }
                        }
                        if (isnewpoint) {
                            newseries = new Object();
                            count = additions[i].count;
                            newseries['name'] = additions[i].name;
                            for (j=0;j<length;j++) {
                                newseries['data'].push(0);
                            }
                            newseries['data'].push(count);
                            chart.series.push(newseries);
                        }
                    }
                    //we have now looped through and added a new data point to all species where new data was created in this pull.  We still need to add a new point to those that were not affected.
                    existingdata = chart.series;
                    for (i=0;i<existingdata.length;i++) {
                        getname = existingdata[i].name;
                        getlength = existingdata[i].data.length;
                        if (getlength<length) { //which we established earlier as one MORE than existed previously, prior to the addition
                            point = [now.getTime(),0]
                            chart.series[i].addPoint(point, true, shift);
                        }
                    }
                }
                setTimeout(getBirds,10000);
            });
        }
    });
</script>

</html>

我遇到的問題非常簡單(但讓我瘋了!),並且在js區塊的早期。 雖然我將變量'chart'定義為新的Highcharts圖表,並且我將'getBirds'設置為加載后加載的函數,但console.log行告訴我圖表未定義,並且下面的行它拋出一個錯誤( Uncaught TypeError: Cannot read property 'series' of undefined )。

我檢查過以下內容:

  1. Highcharts參考( http://www.highcharts.com/docs/working-with-data/preprocessing-live-data ),它建議類似於我的設置;
  2. 我已經嘗試在自己的行上定義chart變量(當然為我的console.log定義了圖表,但沒有定義下一行所需的chart.series );
  3. 我已經研究了stackoverflow和其他可變范圍的文檔,但我認為我正在根據我的研究正確處理它。
  4. 我試過反轉順序 - 將getBirds()函數放在chart定義之上。

我不知所措。 提供任何幫助非常感謝; 提前致謝!

原因很可能是您在聲明階段不能引用變量。 我猜測正在聲明加載函數被調用。 幸運的是,您可以在函數聲明期間引用該對象。 請嘗試以下代碼塊。

function getBirds(e) {
    var now = new Date(),
        et = now.getTime() / 1000, //PHP TS
        st = et - 10, //30 seconds prior in PHP
        chart = this;
    if (chart.series.length > 0) {

...在var塊里面聲明chart變量。

從高亮度頁面嘗試示例我發現變量chart只有在$.json()$ajax()調用之后才可用。 如果您在此之前嘗試使用chart ,則返回undefined 因為它是,它只在$ .json()之后設置。

他們使用json或ajax的示例是這樣設置的:

var chart;

function requestData() {...}

$(document).ready(function() {
        chart = new Highcharts.Chart({
            chart: {
                renderTo: 'chart_container',
                defaultSeriesType: 'spline',
                events: {
                    load: requestData
                }
   ...
});

我和你的例子做了類似的事情。 getBirds()我在json調用之前注釋掉了一些行:

        console.log(chart);
        if (chart.series.length > 0) {
            var series = chart.series[0];
            var length = series.length + 1;
            var shift = series.data.length > 20;
        }

並在json召喚之后移動它們。

並改變了這一行:

                    //newdata['name'] = species;
                    newdata['name'] = scode;

並停在這里:

                    for (j=0;j<length;j++) {

因為錯誤:

Uncaught TypeError: Cannot call method 'push' of undefined

在線

newseries['data'].push(count);

它失敗,因為沒有數組。 希望這有幫助。

在全局命名空間中存在圖表對象之前解釋函數聲明

如果您將語法更改為函數表達式

var getBirds=function() {
    ....
};

在你打電話之前不會對它進行評估。

但是,您可能希望將圖表添加為getBirds()的參數,它比從全局命名空間獲取變量要便宜一些。

編輯

這可能需要一些調試,但值得一試

    var getBirds = function(chart) {
               ...
            };
    $(document).ready(function() {
        chart = new Highcharts.Chart({
            chart: {
                renderTo: 'chart_container',
                defaultSeriesType: 'line',
                events: {
                    load: function() { 
                                     getBirds(this); 
                                     }
                }
            }
            ...
        });

        setTimeout(getBirds,10000);
    });
    }
});

你應該檢查兩個解決方案:

  1. 系列變量屬性不應該是空數組也許可以輸入系列:null;

  2. 用這段代碼替換你的腳本並再次檢查:

http://notepad.cc/share/3TwgCoEano

<script type="text/javascript">
$(function() {
    $(document).ready(function() {
        var chart = new Highcharts.Chart({
            chart: {
                renderTo: 'chart_container',
                defaultSeriesType: 'line',
                events: {
                    load: getBirds
                }
            },
            title: {
                text: 'DRHW Live Data Stream'
            },
            xAxis: {
                type: 'datetime',
                tickPixelInterval: 150,
                maxZoom: 20 * 1000
            },
            yAxis: {
                title: {
                    text: 'Count Observed'
                }
            },
            series: null,
            legend: {
                layout: 'horiztonal',
                align: 'center'
            }
        });
        function getBirds() {
            var now = new Date();
            var et = now.getTime() / 1000; //PHP TS
            var st = et - 10; //30 seconds prior in PHP
            console.log(chart);
            if (chart.series.length > 0) {
                var series = chart.series[0];
                var length = series.length + 1;
                var shift = series.data.length > 20;
            }
            $.getJSON("https://path/to/json&callback=?", function(result) {
                var data = result.data;if (data.length == 0) {
                    return;
                } else {
                    additions = new Array();
                    for (i=0;i<data.length;i++) {
                        if (data[i].qstype != "1") {
                            species = data[i].answers[0]['answer'];
                            scode = species.substring(0,species.search(" - ")).trim()
                            count = (data[i].answers[1]['answer'] * 1);
                            newdata = new Object();
                            newdata['name'] = species;
                            newdata['count'] = count;
                            additions.push(newdata);
                        }
                    }
                    //now, for each addition, you need to loop through the existing data structures, and see if the thing exists.  if it does, add the data; if not, add the thing, then add the data.
                    var existingdata = chart.series;
                    for (i=0;i<additions.length;i++) {
                        isnewpoint = true;
                        for (j=0;j<existingdata.length;j++) {
                            if (existingdata[j].name == additions[i].name) {
                                isnewpoint = false
                                count = additions[i].count;
                                point = [now.getTime(),count];
                                chart.series[j].addPoint(point, true, shift);
                                shift = false; //this way, only one shift occurs - the first time through adding a new point to an existing data set. this will control against future shifting, either from other datapoints having new points added, 
                            }
                        }
                        if (isnewpoint) {
                            newseries = new Object();
                            count = additions[i].count;
                            newseries['name'] = additions[i].name;
                            for (j=0;j<length;j++) {
                                newseries['data'].push(0);
                            }
                            newseries['data'].push(count);
                            chart.series.push(newseries);
                        }
                    }
                    //we have now looped through and added a new data point to all species where new data was created in this pull.  We still need to add a new point to those that were not affected.
                    existingdata = chart.series;
                    for (i=0;i<existingdata.length;i++) {
                        getname = existingdata[i].name;
                        getlength = existingdata[i].data.length;
                        if (getlength<length) { //which we established earlier as one MORE than existed previously, prior to the addition
                            point = [now.getTime(),0]
                            chart.series[i].addPoint(point, true, shift);
                        }
                    }
                }
                setTimeout(getBirds,10000);
            });
        }
    });
});
</script>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM