I can't return my json object

2019-08-20 17:15发布

问题:

I'm having trouble returning a JSON object, instead all I get is an undefined variable.

This code is supposed to return a json element from an API. It seems to work in the success: function, but once I try and take that data elsewhere it just displays 'undefined'

var datas;
datas = getdata();
//getdata();
createChart(datas)

alert('2datass'+datas); // this returns undefined

function createChart(data){
    alert(data); //outputs undefined
}

function getdataaa(){
    alert('ajax');
    $.ajax({
        type: "GET",
        dataType: "json",
        url: "API URL",
        success: function(data){

            alert(data); // WORKS! and outputs my JSON data
            /*
              for(var i =0;i <= data.length-1;i++)
              {
              var item = data[i];

              datas = datas + {
              type: 'column',
              name: item.name,
              data: [item.difference]
              };
              }
            */

            //Neither of these returns seems to work
            return jQuery.parseJSON(data);
            return data;
        }
    });
};

Any help would be appreciated.

SOLUTION

Thanks to all who have helped.

This seems to do the trick

        var datas;
        datas = getData();
        //getdata();

        alert('2datass'+datas);
        console.log(datas);
        createChart(datas);


        function createChart(data){

            alert('createChart'+data);
            var dynamicData;


                    for(var i =0;i <= data.length-1;i++)
                    {
                        var item = data[i];

                        dynamicData = dynamicData + {
                            type: 'column',
                            name: item.name,
                            data: [item.difference]
                        };

                    }

            alert('dynamic' +dynamicData); // works, but says undefined before - outputs dynamic undefined[object Object][object Object][object Object][object Object][object Object]



            var series = [dynamicData,{
                    type: 'column',
                    name: 'Jane',
                    data: [300, 30]
                }, {
                    type: 'column',
                    name: 'John',
                    data: [-200, 50]
                }, {
                    type: 'column',
                    name: 'Joe',
                    data: [444, -25]
                }, {
                    type: 'column',
                    name: 'Jobe',
                    data: [444, -25]
                }, {
                    type: 'column',
                    name: 'Jooe',
                    data: [444, -25]
                },{
                    type: 'column',
                    name: 'Jane',
                    data: [300, 30]
                }
                , {
                    type: 'pie',
                    name: 'Total consumption',
                    data: [{
                            name: 'Jane',
                            y: 13
                            //color: '#4572A7' // Jane's color
                        }, {
                            name: 'John',
                            y: 23
                            //color: '#AA4643' // John's color
                        }, {
                            name: 'Joe',
                            y: 19
                            //color: '#89A54E' // Joe's color
                        }],
                    center: [30, 80],
                    size: 100,
                    showInLegend: false,
                    dataLabels: {
                        enabled: false
                    }
                }];




            var options = {
                chart: {
                    renderTo: 'container'
                },
                title: {
                    text: 'Account Managers Leaderboard'
                },
                xAxis: {
                    categories: ['Month on Month', 'Day on Day']
                },
                tooltip: {
                    formatter: function() {
                        var s;
                        if (this.point.name) { // the pie chart
                            s = ''+
                                this.point.name +': '+ this.y +' sales';
                        } else {
                            s = ''+
                                this.x  +': '+ this.y;
                        }
                        return s;
                    }
                },
                labels: {
                    items: [{
                            html: 'Total proportion of sales <br />this month',
                            style: {
                                left: '40px',
                                top: '-5px',
                                color: 'black'
                            }
                        }]
                },
                series: series
            };

            $(document).ready(function() {
                var chart;
                chart = new Highcharts.Chart(options);
            });

        }



       function getData(){
            //alert('ajax');

            var receivedData; // store your value here
            $.ajax({
                type: "GET",
                dataType: "json",
                url: "API URL",
                async: false,
                success: function(data){
                    alert('data'+data); //works
                    receivedData = data;
                }
            }); 

            return receivedData;
        };

回答1:

The problem is that you return from success function, not your getdataaa function. getdataaa doesn't have a return statement, so it returns undefined by default. Return statement refers to the nearest function.

success: function(data){
   alert(data); // WORKS! and outputs my JSON data
   ...
   //Neither of these returns seems to work
   return jQuery.parseJSON(data);
   return data;
}

This is what you get. You can get your result using a closure like this:

function getdataaa(){
    alert('ajax');

    var receivedData; // store your value here
    $.ajax({
        type: "GET",
        dataType: "json",
        url: "API URL",
        async: false,
        success: function(data){

            alert(data);

            // ...

            receivedData= data;
        }
    });

    return receivedData;
};


回答2:

AJAX calls are asynchronous by default, you have to use the following method to return the response from an ajax call:

function getdataaa() {
    return $.ajax({ 
        type: "GET",
        dataType: "json",
        url: "API URL",
        async: false // NOTICE THIS
    }).responseText; // AND THIS
};

I'm not sure if the responseText will be parsed or unparsed JSON but see where you get from there.



回答3:

Instead of:

 return jQuery.parseJSON(data);

OR

 return data;

call directly the createChart function:

createChart(data)