Google Apps Script return object in Code.gs

2019-08-09 17:01发布

问题:

Is it not possible to return an object in Google Apps Script from server-side? My code is as follows:

function getAllEventsOfDate(){
  var cal = CalendarApp.getCalendarById(Session.getActiveUser().getEmail());
  var events = cal.getEventsForDay(new Date());
  var results = [];
  for(var i = 0; i < events.length;i++){
    var event = {title:events[i].getTitle(), desc:events[i].getDescription(), location:events[i].getLocation(), startTime:events[i].getStartTime(), endTime: events[i].getEndTime()}; 
    results.push(event);
  }
  Logger.log(results);
  return results;
}

In my HTML (called Agenda.html) I have this:

$(document).ready(function(){
  google.script.run.withSuccessHandler(getAgendaData).getAllEventsOfDate();
 });

function getAgendaData(data)
{
    console.log(data);
}

This should just return the objects I have defined from the events data in an array. This does not work however, I'm getting an error that the script has completed succesfully, but the returned value is not a valid return type. If I change the return statement to return results[0];, it doesn't work either (wanted to check if it was caused by the array). If I change it to return results[0].title; it does work: the title of the first event of my calendar is displayed in the console. Does this mean I can't return objects? Any help would be much appreciated.

My Code.gs doGet has this:

function doGet(){
    return HtmlService.createTemplateFromFile('Agenda').evaluate();
}

Update

I found it myself, apparently Date-types are not a legal parameter-type or return-type (this also applies to variables in arrays, objects, ...). I have changed every Date that I use as parameter or return-type to .toString(), and now it works. With these date-strings I can create Date-objects for those dates as well.

回答1:

The .gs script can return an object. From your update it looks like you found the problem.