JavaScript函数数组返回undefined

时间:2015-08-10 21:31:23

标签: javascript arrays ajax

我正在使用AJAX来获取数据并将它们变成如下所示的数组:

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.')
    }
});
}

然后,当我试图调用该函数时,它返回“undefined”。我实际上想把这个数组放到FullCalendar中,如下所示:

  $(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!");
      });

我阅读了大多数类似的问题,似乎我应该使用回调函数,但我真的不明白如何使用它们。

非常感谢!欢迎任何帮助!

1 个答案:

答案 0 :(得分:0)

问题是您执行异步的AJAX请求,并且您无法从drawDate()函数返回此数据。在“成功”回调中,您需要使用从服务器检索到的数据来执行您所需的操作。如下:

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

}