我写了一个谷歌应用程序的脚本代码,它会打开一个谷歌的电子表格,并按行列出值,但有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());
}
你不应该在这种情况下获得个人价值。在这种情况下,您不需要获取单个值,因为'index'是行,并且行都是连续的。如果你需要获得不连续的行,那就不一样了。您正在对同一个服务器端功能进行多个快速调用。在这种情况下,无法保证服务器端函数返回值的顺序。同一个函数的多个实例同时运行。它们不一定按顺序完成,因为服务器端功能可以同时运行。 –
相关:http://stackoverflow.com/questions/35749500/client-javascript-receiving-outdated-values-from-server-side-document-set-and-fe/35752170 –