简体   繁体   中英

google.script.run returns undefined array

I am trying to return an array from my server side function getPrepList(). When accessing from the client side 'prepList[]' returns 'undefined'. This is just a snippet of the full code.gs file.

//< code.gs >//

function getPrepList(){
   var sheet = SpreadsheetApp.getActiveSpreadsheet();
   var doPrepRange = sheet.getRange('F:F');
   var itemNameRange = sheet.getRange('A:A');
   var prepList = new Array();

    for(var i = 1; i < getFirstEmptyRow(); i++){
      if(doPrepRange.getCell(i,1).getValue() == true){
        prepList.push(itemNameRange.getCell(i, 1).getValue());
      };
    };
    Logger.log(prepList);
   return(prepList);
 };


function doGet(){
  return HtmlService.createHtmlOutputFromFile('index');
}; 

// < index.html > //

<!DOCTYPE html>
<html>
  <head>
    <base target="_top">
  </head>
  <body>
    <h1><div align="center">PREP LIST MAKER v 2.0</h1></div>

    <button align="center" onClick="createCountSheet()">Nightly Count Sheet</button><br />
    <button align="center" onClick="showPrepList()">Get Prep List</button><br />

    <script>

    console.info("before execution");
    function createCountSheet(){
      google.script.run
        .generateCountSheet();
     };

     google.script.run 
       .withSuccessHandler(showPrepList)
       .getPrepList();

    function showPrepList(prepList){
      console.log(prepList);
    };

     </script>
  </body>
</html>

Try it this way:

function getPrepList(){
  var ss=SpreadsheetApp.getActive();
  var sh=ss.getActiveSheet();;
  var rg=sh.getDataRange();
  var vals=rg.getValues();
  var prepList=[];
  for(var i=1;i<vals.length;i++){
    if(vals[i][5]){
      prepList.push(vals[i][0]);
    }
  }
  return prepList;
}

It's not clear to me what sheet you wanted so I just picked the active one. I assumed you have a header row so I started the loop at one instead of zero. By the way I did not test this so you may have to tweak it a little.

If you're calling showPrepList(prepList) from a button,

<button align="center" onClick="showPrepList()">Get Prep List</button><br />

prepList will be undefined , because you aren't passing any argument as prepList .

Try,

<button align="center" onClick="showPrepListFromSheet()">Get Prep List</button><br />

<script>

console.info("before execution");
 function showPrepListFromSheet(){
 google.script.run 
   .withSuccessHandler(showPrepList)
   .getPrepList();
function showPrepList(prepList){
  console.log(prepList);
};
}</script>

To read:

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