Server side code not working in google app script

2019-08-20 19:39发布

问题:

Hi I am trying to do a simple thing: 1) create two links in my HTML page 2) When user clicks on link1- I want it to call a server side function that displays "Hello World". But when i click on link1- I am not able to see "Hello World" getting displayed anywhere. I have tried doing this multiple times with different variations but it is not working. Thanks in advance !!

Here is my code

Code.gs

function doGet() {
  return HtmlService.createTemplateFromFile('IndexHTML').evaluate()
      .setTitle('Simple App')
      .setSandboxMode(HtmlService.SandboxMode.IFRAME);
}

function doSomething(){
   return ContentService.createTextOutput('Hello World');
}

IndexHTML.html

<!DOCTYPE html>
<html>
<head>
<?!= HtmlService.createHtmlOutputFromFile('Stylesheet').getContent(); ?>
</head>
<body>

<h1>Simple App</h1>
<p>
 Click on the buttons to view roles
</p>

<a href = "#" id = "index1" >I am index1</a>
    <a href = "#" id = "index2" >I am index2</a>

<?!= HtmlService.createHtmlOutputFromFile('JavaScript').getContent(); ?>

</body>
</html>

JavaScript.html

<!-- Load the jQuery and jQuery UI libraries. -->
<script src="https://code.jquery.com/jquery-1.8.3.min.js"></script>
<script src="https://code.jquery.com/ui/1.10.0/jquery-ui.min.js"></script>

<!-- Custom client-side JavaScript code. -->
<script>
$(document).ready(function() {
    $("#index1").click(function() {
       google.script.run.doSomething()     ;
}

    });
});
</script>

Stylesheet.html

<!-- Load the jQuery UI styles. -->
<link rel="stylesheet" type="text/css" href="https://code.jquery.com/ui/1.10.0/themes/base/jquery-ui.css" />

<!-- Custom styles. -->
<style>
body
{
background-color:red;
}
</style>

回答1:

You are not seeing "Hello World" displayed anywhere because you have not written any code to display it!

All your code does is run server-side doSomething() function, which returns text output. You need to add a success handler to your google.script.run and specify a callback function to run after the server-side function returns successfully, e.g:

google.script.run.withSuccessHandler(processResult).doSomething();

Then write a processResult() javascript function that accepts server return as first argument and does whatever you need to do with it, i.e.:

function processResult(data) {
  console.log(data);
}

See google.script.run reference and HTML Service success handlers reference for more details.