未定义的变量javascript;虽然实际定义

时间:2017-01-05 09:56:02

标签: javascript ajax

我遇到了这段代码的问题:

google.charts.load('current', {
    packages: ['corechart', 'line']
});
google.charts.setOnLoadCallback(drawBasic);

function time(dati) {
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            dati = [];
            dati.push(JSON.parse(this.responseText));
            console.log(dati); //logs perfectly fine
            return dati;
        };
    };
    xmlhttp.open("GET", "graph-data.php", true);
    xmlhttp.send();
};
time();
console.log(dati); // logs nothing

function drawBasic(dati) {

    var data = new google.visualization.DataTable();
    data.addColumn('number', 'X');
    data.addColumn('number', 'Prijs');

    console.log(dati); //logs nothing

    data.addRows(dati);

    var options = {
        hAxis: {
            title: 'Time'
        },
        vAxis: {
            title: 'Prijs'
        }
    };

    var chart = new google.visualization.LineChart(document.getElementById('chart_div'));

    chart.draw(data, options);
}

未定义变量。我该如何定义它们?

1 个答案:

答案 0 :(得分:2)

您收到该错误是因为dati是一个未声明的变量,您试图获取第17行的值:

console.log(dati);

该代码没有范围内的dati标识符。您的dati函数中有一个time 参数,但仅限于time函数内;上面的一行在它之外。

解决了这个问题后,您的下一个问题就在这里:How do I return the response from an asynchronous call? time 启动一个尚未完成的异步操作当time返回时。

您似乎也希望setOnLoadCallback能够将某些内容传递给您的drawBasic函数:

google.charts.setOnLoadCallback(drawBasic);

我无法找到它的文档(!!),但是this page's examples没有显示它接受任何参数所调用的函数。

猜测了一下,但我怀疑你想做这样的事情;见内联评论:

// A scoping function so we don't create globals
(function() {
    // Variables for the data and a loaded flag
    var dati = null;
    var loaded = false;

    // A function we can call from both async operations to see if both have completed
    function checkReady() {
        if (dati && loaded) {
            // They're both done, we can draw
            drawBasic(dati);
        }
    }

    // Load charts and get callback when done
    google.charts.load('current', {
        packages: ['corechart', 'line']
    });
    google.charts.setOnLoadCallback(function() {
        loaded = true;
        checkReady();
    });

    // Load our data
    function time() { // <== Note no `dati` parameter, we want to use the variable declared above
        var xmlhttp = new XMLHttpRequest();
        xmlhttp.onreadystatechange = function() {
            if (this.readyState == 4 && this.status == 200) {
                // Fill in the data -- are you sure you really want an array with the data
                // as its only entry?
                dati = [];
                dati.push(JSON.parse(this.responseText));

                // If we're ready, draw
                checkReady();
            };
        };
        xmlhttp.open("GET", "graph-data.php", true);
        xmlhttp.send();
    };
    time(); // Start the data load

    function drawBasic(dati) {

        var data = new google.visualization.DataTable();
        data.addColumn('number', 'X');
        data.addColumn('number', 'Prijs');

        console.log(dati); //logs nothing

        data.addRows(dati);

        var options = {
            hAxis: {
                title: 'Time'
            },
            vAxis: {
                title: 'Prijs'
            }
        };

        var chart = new google.visualization.LineChart(document.getElementById('chart_div'));

        chart.draw(data, options);
    }
})(); // The end of the scoping function, and `()` to invoke it

我确信这并不完美,但希望它能让你以正确的方式前进。