【问题标题】:Google script return from code.gs to index.htmlGoogle 脚本从 code.gs 返回到 index.html
【发布时间】:2016-03-30 08:58:50
【问题描述】:

如何将 code.gs 中的内容返回到 index.html。

我已经在“Index.html”中尝试过这个,但这不起作用。

index.html

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

代码.gs

function getAmountOfImages()
{
  return "Tom"
}

请帮忙。

【问题讨论】:

    标签: javascript jquery google-apps-script


    【解决方案1】:

    根据documentation

    "google.script.run 是一个异步客户端 JavaScript API 在可以调用服务器端应用程序脚本的 HTML 服务页面中可用 函数。”

    因此您的结果将在回调中返回。所以你将不得不使用处理函数,即withFailureHandlerwithSuccessHandler

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

    res成功处理回调函数中的参数将保存来自谷歌应用脚​​本的响应。

    【讨论】:

      【解决方案2】:

      google.script.run 是您所需要的。

      请参见下面的示例。

      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>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-07-16
        • 2016-03-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多