简体   繁体   中英

How to return values correctly using withSuccessHandler

I'm again having some trouble with google.script.run, this time, I want to retrieve data from a spreadsheet. If you see an error, feel free to write it in the answers.

By the way, here are some bits of the code that I used:

Html Code:

alert(GetData(0, 1, 1));

function GetData(Page, GetRow, GetColumn)
  {
    var DataExtracted;
    google.script.run.withSuccessHandler(function(Data){DataExtracted = Data;}).GetCellValue({PageNum: Page, Row: GetRow, Column: GetColumn});
    return DataExtracted;
  }

Gs Code:

var Server = SpreadsheetApp.openByUrl('https://docs.google.com/spreadsheets/d/...');
//I'm not writing the Url, because of privacy
var Pages = Server.getSheets();
function GetCellValue(Object)
{
  return Pages[Object.PageNum].getRange(Object.Row, Object.Column).getValue();
}

Html:

<script>
var DataExtracted;
function GetData(Page, GetRow, GetColumn) {
    google.script.run
    .withSuccessHandler(function(Data){
       DataExtracted=Data;//DataExtracted is global and available to other functions
       window.alert(Data);
    })
    .GetCellValue({PageNum: Page, Row: GetRow, Column: GetColumn});    
  }
</script> 

GS:

function GetCellValue(Object) {
  const ss=SpreadsheetApp.getActive();
  const sh=ss.getSheets()[Object.PageNum];//assuming numbers start at zero
  return sh.getRange(Object.Row, Object.Column).getValue();
}

Normally there are atleast a few seconds between calling the server function and calling the withSuccessHandler. You can use gData in other functions. It's the value returned from the server function getCellValue();

var DataExtracted;
GetData(0, 1, 1);
alert(DataExtracted);
function GetData(Page, GetRow, GetColumn)
  {
    google.script.run.withSuccessHandler(function(Data){DataExtracted = Data;}).GetCellValue({PageNum: Page, Row: GetRow, Column: GetColumn});
  }

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