javascript - 谷歌应用 json 数据从 code.gs 到 html 下拉列表
问题描述
我正在创建一个谷歌应用程序脚本,并试图将 json 数据从 code.gs 放到 html 文件下拉列表中。我真的不知道这是如何通过对 JS 和谷歌自己的东西没有那么丰富的经验来完成的。继承人的代码:
function PopulateDropDownList() {
var url = 'url for the api call'
var res = UrlFetchApp.fetch(url, {'api stuff here, it works i have tested it'}})
var json = res.getContentText()
var txt = JSON.parse(json)
people = txt.data.map(function (a) {
return [a.firstName, a.lastName];
})
Logger.log(people)
return people
}
问题是,如何将“人员”列表添加到 html 下拉选择中?我知道它与脚本标签有关,但我真的不知道该怎么做。我也尝试过 goolge.script.run.myFunction 但我不知道如何从那里取得进展
编辑:
HTML 文件
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<select id="droplist">
</select>
<script>
(function () {
google.script.run.withSuccessHandler(
function(people) {
var select = document.getElementById("droplist");
for( var dude of people) {
var option = document.createElement("option");
// option.text = dude.firstName + " " + dude.lastName;
option.text = dude[0] + " " + dude[1];
select.add(option);
}
}
).get_people();
}());
</script>
</body>
</html>
代码.gs:
function getPeople() {
/*json stuff here*/
var json = res.getContentText()
var txt = JSON.parse(json)
var people = txt.data.map(function (a) {
return [a.firstName, a.lastName]
})
Logger.log(people)
return people
}
function showDialog() {
var html = HtmlService.createTemplateFromFile("Page").evaluate();
// return html;
SpreadsheetApp.getUi().showModalDialog(html, "List");
}
function onOpen() {
SpreadsheetApp.getUi()
.createMenu('choose person')
.addItem('search', 'showDialog')
.addToUi();
}
解决方案
我猜您正在使用HtmlService
. 如果是这样,您可以使用模板来动态生成 HTML。在您的项目中创建一个新的 HTML 文件并使用scriptlet生成您想要的 HTML。
这是一个带有select
标签的简单示例:
Code.gs
function doGet(e) {
const template = HtmlService.createTemplateFromFile('Template')
template.people = getPeople()
return template.evaluate()
}
function getPeople() {
const url = 'url for the api call'
const res = UrlFetchApp.fetch(url, {'api stuff here, it works i have tested it'}})
const txt = JSON.parse(res.getContentText())
return txt.data.map(function (a) {
return [a.firstName, a.lastName]
})
}
Template.html
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<select>
<? for (let person of people) { ?>
<option><?= person[1] ?>, <?= person[0] ?></option>
<? } ?>
</select>
</body>
</html>
参考
推荐阅读
- python - 如何将信息从一个类的实例继承到另一个实例中?
- python - 如何分割弯曲的道路/车道/路径/轨道/对象等?
- javascript - 如何在javascript中禁用按钮上启用工具提示?
- mysql - 更新时重复输入
- powershell - Powershell foreach循环读取csv,操作并写入txt
- firebase - 无法将我的数据上传到 firebase
- tensorflow - tensorlfow的model.fit()方法中steps_per_epoch和batch size有什么区别?
- javascript - 如何获取完整日历的开始时间和结束时间
- string - 预期 &str 发现 char 生锈?
- python-3.x - Synology DS218j 中的 Python 模块