2016-06-17 84 views
0

我写了一个谷歌应用程序的脚本代码,它会打开一个谷歌的电子表格,并按行列出值,但有2个问题: 1.按随机顺序输出。 2. id“loding”变成“Finished!”的div文本在列出所有值之前。 我以为脚本将等待服务器端函数返回时,我通过“withSuccessHandler()”运行它,但事实并非如此。 我该如何纠正它?如何同步调用google apps脚本服务器端函数?

的index.html:

<!DOCTYPE html> 
<html> 
    <head> 
     <base target="_top"> 
     <script> 
      function jsListValue() { 
       // Get count. 
       google.script.run.withSuccessHandler(function(count) { 
        // List all values. 
        for(count; count>0; count=count-1) { 
         // Get a value. 
         google.script.run.withSuccessHandler(function(content) { 
          // Shows in "output". 
          var new_div = document.createElement("div"); 
          new_div.appendChild(document.createTextNode(content)); 
          document.getElementById("output").appendChild(new_div); 
         }).gsGetValue(count); 
        } 
        // Change loding notice. 
        document.getElementById("loding").innerHTML = "Finished!"; 
       }).gsGetCount(); 
      } 
     </script> 
    </head> 
    <body onload="jsListValue()"> 
     <div id="output"></div> 
     <div id="loding">Loding now...</div> 
    </body> 
</html> 

code.gs

function    doGet() { 
    return HtmlService.createHtmlOutputFromFile('index').setSandboxMode(HtmlService.SandboxMode.IFRAME); 
} 
function    gsOpenSheet() { 
    // Return sheet of the note data. 
    return (SpreadsheetApp.openById("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx").getSheetByName("sheet1")); 
} 
function    gsGetCount() { 
    // Return last row index in this sheet. 
    return (gsOpenSheet().getLastRow()); 
} 
function    gsGetValue(index) { 
    // Return value in the (index,1). 
    return (gsOpenSheet().getRange(index,1).getValue()); 
} 
+0

你不应该在这种情况下获得个人价值。在这种情况下,您不需要获取单个值,因为'index'是行,并且行都是连续的。如果你需要获得不连续的行,那就不一样了。您正在对同一个服务器端功能进行多个快速调用。在这种情况下,无法保证服务器端函数返回值的顺序。同一个函数的多个实例同时运行。它们不一定按顺序完成,因为服务器端功能可以同时运行。 –

+0

相关:http://stackoverflow.com/questions/35749500/client-javascript-receiving-outdated-values-from-server-side-document-set-and-fe/35752170 –

回答

2

GAS是非常相似的JavaScript和谷歌的服务器端函数的调用是异步的。你不能改变这个(至少我没有看到任何文档注册表)。

你可以做的是,在客户端使用回调函数来轮询服务器以获得“成功”返回值。它会继续轮询它说1分钟,否则退出。如果服务器返回成功值,让它将客户端标志设置为“true”。除非国旗是真实的,否则客户端应该没有任何进展。通过这种方式,您可以控制客户端发生的情况。

+0

Apps脚本有一个内置的方式来处理这,看到我的回答下面 – howMuchCheeseIsTooMuchCheese

+0

@howMuchCheeseIsTooMuchCheese好,这是记录的方法。但是服务器端功能仍然是异步调用的,不像OP想要的那样。 –

0

你想用withSuccessHandlerDocs

<!DOCTYPE html> 
<html> 
    <head> 
    <base target="_top"> 
    <script> 
     function onSuccess(numUnread) { 
     var div = document.getElementById('output'); 
     div.innerHTML = 'You have ' + numUnread 
      + ' unread messages in your Gmail inbox.'; 
     } 

     google.script.run.withSuccessHandler(onSuccess) 
      .getUnreadEmails(); 
    </script> 
    </head> 
    <body> 
    <div id="output"></div> 
    </body> 
</html> 
相关问题