我正在尝试在Google表格边栏中显示来自服务器功能的数据。我使用成功处理程序对服务器进行异步调用,但客户端以某种方式接收空值。尽管在客户端 - 服务器通信方面进行了广泛的搜索,但我还是没能弄清楚原因。
目前,服务器函数末尾的日志显示对象'flags'已完全定义,但successHandler'showErrors'开头的控制台日志表明'flags'未定义。
我检查了HTML服务上的Google文档,据我所知,'flags'是一个有效的返回值,因为它是一个包含整数,字符串和字符串数组的对象。我尝试从一个对象更改'flags',这是一个简单的字符串,它仍然在'showErrors'中未定义。 有人知道为什么服务器和客户端之间的“标志”内容会丢失吗?提前致谢!
HTML:
<form onsubmit="google.script.host.close()">
<div id="intro" style="font-style:italic">
<p><b>Title</b><br><br>
Introduction text</p>
<HR>
<input type="button" style="button" id="start" value="Start" onclick="hideDiv('intro');google.script.run.withSuccessHandler(showErrors).checkList2(0,0)"> <!-- Intro starts loop -->
</div>
<div id="showErrors"></div>
</form>
<script>
function showErrors(flags){
console.log('client side flags:');
console.log(flags);
var div = document.getElementById('showErrors');
div.innerHTML = '<p style="font-style:italic">';
div.innerHTML += 'Sheet '+flags.pageNum+' of '+flags.numPages+'.';
//... more div.innerHTML += ...
div.innerHTML += '<input type="button" style="button" value="Next" onclick="google.script.run.withSuccessHandler(showErrors).checkList2('+Number(flags.pageNum)+1+','+flags.totalErrors+')"';
div.innerHTML += '<input type="submit" style="button" value="Cancel">';
}
function hideDiv(div){
document.getElementById(div).innerHTML=''; // clear div
}
</script>
服务器功能:
function checkList2(nComplete,nErrors){
var nSheets=21;
nComplete = Number(nComplete);
nErrors = Number(nErrors);
var results = errorList(nComplete); // Get results.name (string) and results.errors (array)
var errors = results.errors;
if (errors=='') {
checkList2(nComplete+1,nErrors); // Move on to next sheet
} else {
nErrors = nErrors + errors.length;
var flags = {};
flags.numErrors = errors.length;
flags.totalErrors = nErrors;
flags.pageNum = nComplete;
flags.numPages = nSheets;
flags.sheetName = results.name;
flags.errors = errors;
Logger.log('server side flags:')
Logger.log(flags)
return flags;
}
}
答案 0 :(得分:1)
如果您输入此if
块,则不会向客户返回任何内容:
if (errors=='') {
checkList2(nComplete+1,nErrors); // Move on to next sheet
// no return
} else {
nErrors = nErrors + errors.length;
var flags = {};
flags.numErrors = errors.length;
flags.totalErrors = nErrors;
flags.pageNum = nComplete;
flags.numPages = nSheets;
flags.sheetName = results.name;
flags.errors = errors;
Logger.log('server side flags:')
Logger.log(flags)
return flags;
}
您需要做的就是返回递归调用,我认为您将获得您期望的行为。
if (errors=='') {
return checkList2(nComplete+1,nErrors); // Move on to next sheet
} else {
nErrors = nErrors + errors.length;
var flags = {};
flags.numErrors = errors.length;
flags.totalErrors = nErrors;
flags.pageNum = nComplete;
flags.numPages = nSheets;
flags.sheetName = results.name;
flags.errors = errors;
Logger.log('server side flags:')
Logger.log(flags)
return flags;
}