简体   繁体   English

如何使用 withSuccessHandler 正确返回值

[英]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.我又遇到了 google.script.run 的问题,这一次,我想从电子表格中检索数据。 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: Html 代码:

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: GS代码:

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: 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: 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.通常在调用服务器 function 和调用 withSuccessHandler 之间至少有几秒钟的时间。 You can use gData in other functions.您可以在其他功能中使用 gData。 It's the value returned from the server function getCellValue();是服务器返回的值 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});
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM