JavaScript Variable and passing data issues

2019-09-17 19:48发布

I have an issue in that the $.getJSON segment of code works fine and produces a variable called 'zippy'. I need to access 'zippy' under 'series: data' further down in the code.

I have tried a number of things unfortunately i can't make it work. The easiest would be way to 'return data' $.getJSON(jsonUrl,function(zippy) out of the funcation(zippy) call but I'm lost as to how to make that data available.

$(function() {
    $(document).ready(function() {
        Highcharts.setOptions({
            global: {
                useUTC: false
            }
        });

        console.log("+++++++++++++++++++++++++++++++++++++");
        var jsonUrl = "http://www.someurl.com/thing.php?callback=?";

        $.getJSON(jsonUrl, function(zippy) {
            for(i = 0; i < zippy.cpmdata.length; i++) {
                console.log("TIMESTAMP: " + zippy.cpmdata[i].timestamp + " AFTER: ");


                zippy.cpmdata[i].timestamp = Date.parse(zippy.cpmdata[i].timestamp).getTime() / 1000;
                //var unixtime  Date.parse(temptime).getTime()/1000

                console.log(" TESST " + zippy.cpmdata[i].timestamp + " \r\n");

            }
        });
        console.log("+++++++++++++++++++++++++++++++++++++");

        var chart;
        chart = new Highcharts.Chart({
            chart: {
                renderTo: 'container',
                type: 'spline',
                marginRight: 10,
                events: {
                    load: function() {

                        // set up the updating of the chart each second
                        var series = this.series[0];
                        setInterval(function() {
                            var x = (new Date()).getTime(), // current time
                                y = Math.random();
                            series.addPoint([x, y], true, true);
                        }, 1000);
                    }
                }
            },
            series: [{
                name: 'Random data',
                data: (function() {
                    // generate an array of random data
                    var data = [],
                        time = (new Date()).getTime(),
                        i;

                    console.log("++NEED ACCESS HERE FOR ZIPPY++");
                    console.log(" =============== \r\n");
                    console.log(" FINAL " + zippy.cpmdata[5].timestamp + " \r\n");
                    return data;
                })()
            }]



        }

2条回答
闹够了就滚
2楼-- · 2019-09-17 20:33

Your problem is that getJSON is asynchronous. What's happening in your code is this:

  1. document.ready is triggered
  2. getJSON is called and registers a callback "function(zippy)" note that getJSON returns immediately without executing the callback
  3. You try to draw a chart using HighCharts

    ... several hundred milliseconds later

  4. The browser makes the JSON request

    ... several hundred milliseconds later

  5. The JSON request returns with data and triggers the callback to "function(zippy)"

  6. "function(zippy)" is executed

So you see. The problem is not how "function(zippy)" is executed but when it is executed. As such, you cannot execute code that wants to use the return value of the JSON request outside of the callback function. (Actually you can but we'll ignore polling with setTimeout or using synchronous ajax for now)

The solution is to move all the code that you want to run later on inside the callback function:

$.getJSON(jsonUrl, function(zippy) {
        for(i = 0; i < zippy.cpmdata.length; i++) {
            console.log("TIMESTAMP: " + zippy.cpmdata[i].timestamp + " AFTER: ");


            zippy.cpmdata[i].timestamp = Date.parse(zippy.cpmdata[i].timestamp).getTime() / 1000;
            //var unixtime  Date.parse(temptime).getTime()/1000

            console.log(" TESST " + zippy.cpmdata[i].timestamp + " \r\n");

        }

        var chart;
        chart = new Highcharts.Chart({
        chart: {
            renderTo: 'container',
            type: 'spline',
            marginRight: 10,
            events: {
                load: function() {

                    // set up the updating of the chart each second
                    var series = this.series[0];
                    setInterval(function() {
                        var x = (new Date()).getTime(), // current time
                            y = Math.random();
                        series.addPoint([x, y], true, true);
                    }, 1000);
                }
            }
        },
        series: [{
            name: 'Random data',
            data: (function() {
                // generate an array of random data
                var data = [],
                    time = (new Date()).getTime(),
                    i;

                console.log(" FINAL " + zippy.cpmdata[5].timestamp + " \r\n");
                return data;
            })()
        }]
    });
查看更多
迷人小祖宗
3楼-- · 2019-09-17 20:34

You need to put all of the new Highcharts.Chart({...}) stuff inside the getJSON callback, because you need to wait until the json request completes before creating the chart. See my code comment that says CUT AND PASTE chart = new Highcharts.Chart({...}) STUFF HERE!!!.

$(document).ready(function() {
    Highcharts.setOptions({
        global: {
            useUTC: false
        }
    });

    console.log("+++++++++++++++++++++++++++++++++++++");
    var jsonUrl = "http://www.someurl.com/thing.php?callback=?";

    $.getJSON(jsonUrl, function(zippy) {
        for(i = 0; i < zippy.cpmdata.length; i++) {
            console.log("TIMESTAMP: " + zippy.cpmdata[i].timestamp + " AFTER: ");


            zippy.cpmdata[i].timestamp = Date.parse(zippy.cpmdata[i].timestamp).getTime() / 1000;
            //var unixtime  Date.parse(temptime).getTime()/1000

            console.log(" TESST " + zippy.cpmdata[i].timestamp + " \r\n");

            // CUT AND PASTE chart = new Highcharts.Chart({...}) STUFF HERE!!!

        }
    });
    console.log("+++++++++++++++++++++++++++++++++++++");

});
查看更多
登录 后发表回答