简体   繁体   中英

Google Apps Script returning a null

I have a google apps script function that is pulling data from a spreadsheet. It is able to log the information happily and then I return the data to a javascript function. But when I try to stringify and alert the information it alerts "null".

Not sure where I am going wrong!

Javascript calling the GAS function:

google.script.run.withSuccessHandler(getNews).getTheNews();

GAS function:

function getTheNews(){

 var ss = SpreadsheetApp.openByUrl(url);
 var ws = ss.getSheetByName("NewsFeed"); 
  
 
  var theNews = ws.getRange(3, 2, ws.getLastRow()-2, 1).getValues();
  Logger.log(theNews);
  
 return theNews;
 
}

The GAS log: 在此处输入图像描述

Javascript function receiving the info:

function getNews(theNews){
var mystr = JSON.stringify(theNews);
            alert(mystr);
}

Issue and workaround:

Unfortunately, it seems that in the current stage, the date object cannot be directly returned from Google Apps Script side to Javascript side. Also I could replicate your situation. I think that this is the reason of your issue. So as the current workaround, how about the following modification?

Modified script:

In this modification, the date object is converted to the string and sent to Javascript side. At Javascript side, the date string is converted to the date object.

HTML & Javascript side:

google.script.run.withSuccessHandler(getNews).getTheNews();

function getNews(theNews){
  theNews = theNews.map(r => r.map(c => new Date(c)));  // Added
  var mystr = JSON.stringify(theNews);
  alert(mystr);
}

Google Apps Script side:

function getTheNews(){
  var ss = SpreadsheetApp.openByUrl(url);
  var ws = ss.getSheetByName("NewsFeed");
  var theNews = ws.getRange(3, 2, ws.getLastRow()-2, 1).getValues();
  return theNews.map(r => r.map(c => c.toISOString()));  // Modified
}
  • I think that in this case, c.getTime() instead of c.toISOString() can be also used.

Note:

  • For example, if you want to retrieve the display values on the cells, you can also modify as follows. In this case, Javascript is not required to be modified.

    • From

       var theNews = ws.getRange(3, 2, ws.getLastRow()-2, 1).getValues();
    • To

       var theNews = ws.getRange(3, 2, ws.getLastRow()-2, 1).getDisplayValues();
  • Also I found this issue at the Google issue tracker. Ref But when I saw the status, it seems "Won't Fix (Intended behavior)".

References:

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