简体   繁体   中英

JavaScript function array return undefined

I am using AJAX to get the data and make them into an array like below:

function drawDate(username, date, device, token){
    $.ajax({
    type: 'GET',
    url: dsu + "dataPoints/" + getDatapointId(username, date, device),
    headers: {
        "Authorization": "Bearer " + token
    },
    success : function(data, device) {
        var location_events = []; //***** Here is the array variable. 
        if(device == "android" || device == "ios") {
            rows = data["body"]["episodes"].map(function (epi) {
                var state = epi["inferred-state"].toLocaleUpperCase();
                var start = new Date(epi["start"]);
                var end = new Date(epi["end"]);
                var long_lat = epi["location-samples"];

                if (state == "STILL") {
                    var longitude_sum = 0;
                    var latitude_sum = 0;
                    long_lat.forEach(function(obj) {
                        longitude_sum += obj['longitude'];
                        latitude_sum += obj['latitude'];
                    });
                    return [state, start, end, latitude_sum / long_lat.length, longitude_sum / long_lat.length];
                }

            });
            //**** I pushed the data into the array.
            rows.forEach(function(obj){
                if (typeof obj !== 'undefined') {
                    location_events.push({
                        title: 'location',
                        start: moment(obj[1]).format().substring(0, 19),
                        end: moment(obj[2]).format().substring(0, 19),
                        url: "https://maps.googleapis.com/maps/api/staticmap?center="+ obj[3] + "," + obj[4] + "&zoom=15&size=2000x1000&maptype=roadmap&markers=color:red%7Clabel:S%7C" + obj[3] + "," + obj[4] + "&markers=size:mid"
                    })
                }
            });
            console.log(location_events);
            return location_events

        }


    },
    error: function(data){
        console.log('Data did not have any locations.')
    }
});
}

Then when I tried to call that function, it returned "undefined". I actually want to put that array into FullCalendar like below:

  $(document).ready(function() {
     var today = moment();
     var token = url("#access_token");
     $.getJSON(dsu + "oauth/check_token?token=" + token)
      .done(function(data) {
          var username = data["user_name"];
          var device = 'android';
          var date = url("#date")? moment(url("#date")).toDate() : new Date();
          var redraw = function(){
              var test = drawDate(username, moment(date).format('YYYY-MM-DD'), device, token);
              console.log(test); //***** Here! I tried to make the return of the function into a variable but it returned "undefined"
          };
          $('#calendar').fullCalendar({
              header: '',
              defaultDate: '2015-08-03',
              defaultView: 'agendaDay',
              allDaySlot: false,
              slotEventOverlap: false,
              events: test, //******* I want to the array to be rendered here.
              eventAfterRender: function(event, element, view) {
                $(element).attr("id", "event_id_" + event.id);
              }
          });
      })
      .fail(function() {
          console.log("Fail!");
      });

I read most of the similar questions and it seems that I should use callback function but I don't really understand how to use them.

Thank you very much! Any help is welcome!

The problem is that you do AJAX request which is asynchronous and you cannot return this data from drawDate() function. You need to do what you need with data retrieved from server in your 'success' callback. Like following:

 success : function(data, device) {
    var location_events = []; //***** Here is the array variable. 
    if(device == "android" || device == "ios") {
        rows = data["body"]["episodes"].map(function (epi) {
            var state = epi["inferred-state"].toLocaleUpperCase();
            var start = new Date(epi["start"]);
            var end = new Date(epi["end"]);
            var long_lat = epi["location-samples"];

            if (state == "STILL") {
                var longitude_sum = 0;
                var latitude_sum = 0;
                long_lat.forEach(function(obj) {
                    longitude_sum += obj['longitude'];
                    latitude_sum += obj['latitude'];
                });
                location_events = [state, start, end, latitude_sum / long_lat.length, longitude_sum / long_lat.length];
            }

        });
        //**** I pushed the data into the array.
        rows.forEach(function(obj){
            if (typeof obj !== 'undefined') {
                location_events.push({
                    title: 'location',
                    start: moment(obj[1]).format().substring(0, 19),
                    end: moment(obj[2]).format().substring(0, 19),
                    url: "https://maps.googleapis.com/maps/api/staticmap?center="+ obj[3] + "," + obj[4] + "&zoom=15&size=2000x1000&maptype=roadmap&markers=color:red%7Clabel:S%7C" + obj[3] + "," + obj[4] + "&markers=size:mid"
                })
            }
        });
        console.log(location_events);


    }
     $('#calendar').fullCalendar({
          header: '',
          defaultDate: '2015-08-03',
          defaultView: 'agendaDay',
          allDaySlot: false,
          slotEventOverlap: false,
          events: location_events,
          eventAfterRender: function(event, element, view) {
            $(element).attr("id", "event_id_" + event.id);
          }
      });

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM