JavaScript Variable and passing data issues

ⅰ亾dé卋堺 提交于 2019-12-13 04:48:47

问题


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;
                })()
            }]



        }

回答1:


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;
            })()
        }]
    });



回答2:


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("+++++++++++++++++++++++++++++++++++++");

});


来源:https://stackoverflow.com/questions/13593551/javascript-variable-and-passing-data-issues

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!