【发布时间】:2019-03-15 01:14:03
【问题描述】:
我是异步调用的新手,我认为这就是问题所在。但是,我不太确定如何修复它,因为 Google Apps 脚本不支持承诺,而且我也不知道如何使用它们。我听说如果在 GAS 中使用 HTML 服务,那么承诺是可能的,这就是我正在使用的。但是,我不知道如何实现这一点。这是我到目前为止所拥有的。 主要问题是我需要将数据显示在下面服务器端 (code.gs) 的第二个 Logger.log 中。数据到达第一个 logger.log (code.gs) 中的函数,但在第二个 logger.log (code.gs) 中显示用户缓存时,该对象为空(非空)。可以使用任何键/数据并且可以复制问题,因此它与异步调用有关,但是如何在 GUI_JS 代码中修复它?
服务器端(code.gs):
// global variable to save into the cache
var userCache = CacheService.getUserCache();
// SAVE OPERATION - saves the checkboxes into the user cache
function processSavedValues(checkboxesObj){
Logger.log(checkboxesObj); // this line shows in Logger
userCache.putAll(checkboxesObj, 20);
var getCache = userCache.getAll(['key1','key2']);
Logger.log(getCache); // this line doesn't show in Logger
}
// Loads the HTML Service of Apps Script
function doGet(request) {
return HtmlService.createTemplateFromFile('index').evaluate();
}
function include(filename) {
return HtmlService.createHtmlOutputFromFile(filename).getContent();
}
客户端(index.html):
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<form>
<fieldset class="columnList">
<div>
<input type="checkbox" id="key1" name="fieldset[]" value="value1">
<label class="checkmark" for="key1">test1</label>
</div>
<div>
<input type="checkbox" id="key2" name="fieldset[]" value="value2">
<label class="checkmark" for="key2">test2</label>
</div>
</fieldset>
</form>
<button onclick="saveAllCheckboxValues()">test</button>
<?!= include('GUI_JS'); ?>
</body>
</html>
客户端使用 HTML 服务 (GUI_JS.html):
<script>
// Saves all checkbox values into the cache
function saveAllCheckboxValues(){
// Select all checkboxes in the document
var allCheckboxes = document.querySelectorAll("input[type=checkbox]");
// Create a Key/Value pairs with the IDs and values of each checkbox
var checkboxesObj = {};
for (var i = 0; i < allCheckboxes.length; i++) {
checkboxesObj[allCheckboxes[i].id] = allCheckboxes[i].checked;
}
// sends the checkbox values server-side into the cache
google.script.run.withSuccessHandler(checkboxSaved).processSavedValues(checkboxesObj);
// displays successfully saved
function checkboxSaved(){
alert("Great Success!");
}
}
</script>
Logger.log 的结果:
[19-03-14 18:28:38:913 PDT] {key1=true, key2=true}
[19-03-14 18:28:38:959 PDT] {}
【问题讨论】:
-
你能粘贴
Logger.log(checkboxesObj); // this line shows in Logger的结果吗 -
当然,你去...
-
这些值与您在其他问题中使用的值相同吗?正如我在我的 cmets & answer 中提到的,以及 Tanaike 在这里提到的,要放置在缓存中的值必须是字符串。
标签: javascript asynchronous google-apps-script web-applications