繁体   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