服务器端代码在谷歌应用脚本中不起作用

Server side code not working in google app script

本文关键字:脚本 不起作用 应用 谷歌 代码 服务器端      更新时间:2023-09-26

嗨,我正在尝试做一件简单的事情:1)在我的HTML页面中创建两个链接2)当用户点击link1时-我希望它调用显示"Hello World"的服务器端函数。但是当我点击链接1时,我无法看到"Hello World"显示在任何地方。我已经尝试使用不同的变体多次执行此操作,但它不起作用。提前感谢!!

这是我的代码

Code.gs

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

索引HTML.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>

样式表.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>

您没有看到"Hello World"显示在任何地方,因为您没有编写任何代码来显示它!

您的代码所做的只是运行服务器端doSomething()函数,该函数返回文本输出。您需要向google.script.run添加一个成功处理程序,并指定在服务器端函数成功返回后运行的回调函数,例如:

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

然后编写一个processResult() javascript 函数,它接受服务器返回作为第一个参数,并执行您需要处理的任何操作,即:

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

有关详细信息,请参阅google.script.run参考和 HTML 服务成功处理程序参考。