简体   繁体   中英

Google script return from code.gs to index.html

How can I return something from code.gs to index.html.

I have tried this in "Index.html", but this doesn't work.

index.html

   $('#test').click(function() {
        alert(google.script.run.getAmountOfImages());
    });

Code.gs

function getAmountOfImages()
{
  return "Tom"
}

Please help.

According to the documentation

"google.script.run is an asynchronous client-side JavaScript API available in HTML-service pages that can call server-side Apps Script functions."

therefore your result will be returned in a callback. So you will have to use Handler functions ie withFailureHandler and withSuccessHandler

google.script.run
    .withFailureHandler(function(err){
        console.error("error occured", e);
    })
    .withSuccessHandler(function(res){
        alert(res);
    })
    .getAmountOfImages();

res Parameter in success handler callback function will hold the response from google app script.

google.script.run is what you need.

See the example below.

code.gs

function runOnGsAndGetValue() {
  return "Hello World!";
}

function runOnGsOnly() {
  Logger.log("Hello World"); // On Appscript go to 'View' -> 'Logs' to see your Logs
}

sample.html

<!DOCTYPE html>
<html>
   <head>
   </head>
   <body>
      <p id="para">Hello World</p>
      <br>
      <button onclick="onlyRun()">Run Code in Code.gs Only</button>
      <br><br>
      <button onclick="runAndGet()">Run Code in Code.gs and Return a Value</button>
      <script>
         function setText(text){
          var div = document.getElementById('para');
          div.innerHTML = text;
         }

         function onSuccess(str) {
           setText(str);
         }

         function onFailure(error) {
           setText("ERROR: " + error.message);
         }


         function runAndGet(){
        google.script.run.withFailureHandler(onFailure).withSuccessHandler(onSuccess).runOnGsAndGetValue();
         }

         function onlyRun(){
           google.script.run.runOnGsOnly();
         }

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

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